I have a weird problem with Http-Requests randomly failing with an Ionic(V3) App using the Http-Client from Angular (7.1.1). The Backend is an ASP.NET Core Web API with CORS configured to allow any Headers, Methods and Origins.
To figure out the problem I switched from Emulator to Browser. After resolving some CORS Issues I noticed that the problem with failing requests only exists in Chrome (FF and Edge are working fine). The HTTP Requests fail with: "ERR_INVALID_HTTP_RESPONSE", after clicking back and forth the network tab looks like this:
I can't explain why some Requests don't have the Preflight request, but those requests seem to always succeed (they also have den header "Accept: application/json, text/plain, /" which should alway trigger the Options-Preflight, if I am correct?)
Also every requests, even the failing ones, reach the backend and resolve successfully on the backend.
The error on the client in the console:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": null,
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for (unknown url): 0 Unknown Error",
"error": {
"isTrusted": true
}
}
Reading the Ionic forums this leads to a CORS problem. Perhaps I overlooked something, so here is my CORS-Configuration from the Backend:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseCors(builder =>
{
builder.WithOrigins("*")
.WithMethods("*")
.WithHeaders("*");
});
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
Any hint is really appreciated.
If your Web API project is on aspnet core 2.2 then it could be related to this issue: Response that returns 204 fails with HTTP_1_1_REQUIRED/INVALID_HTTP_RESPONSE in ANCM In-process
There is three options:
Add the following as the first lines of your StartUp.cs Configure method.
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 204)
{
ctx.Response.ContentLength = 0;
}
});
Also about the preflight not firing everytime, the browser cache includes the results of preflight OPTIONS calls so instead of having to fire a preflight on every request, it only fires once the cache has expired.
Lastly: configuring CORS with an accept of any origin can be unsafe, see:CORS security: reflecting any origin header value when configured to * is dangerous