In Firefox I'm getting this error:
Access to XMLHttpRequest at 'http://localhost:5000/api/Sessions' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Normally this is a problem of the order of the middleware but i've tried to change it and does not work
Startup.cs configure Services:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
Starup.cs Configure
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "User.Manager.Webapi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseAuthorization();
app.UseHttpMetrics();
app.UseMiddleware<JwtMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapMetrics();
});
I think there's a problem with the rest of de middlewares
The problem isn't with the middleware itself. According with Microsoft documentation, you're doing it correctly.
The problem is that you're doing the API call through the HTTP port (5000) and your API due to the following line of code forces HTTP requests to be redirected to HTTPS (Under the hood it adds the HttpsRedirectionMiddleware).
app.UseHttpsRedirection();
Your preflight request is made through HTTP, which your API tries to redirect to HTTPS and it fails. You can read more here.
So, you have either two solutions:
Make your client side app using the HTTPS port (5001) to call your API.
Add this middleware in all environments but development - This is what I typically do on my projects.
if (!env.IsDevelopment())
{
app.UseHttpsRedirection();
}