rafaetti
rafaetti

Reputation: 5

ASP Net Core CORS error during put request

I'm currently developing a ASP Net Core API, and when I try to send a PUT request for the server I get the return error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

I've all ready set the app.EnableCors() and services.EnableCors(), but even after that I get the error message.

Here is the code:

public class CorsMiddleware
{
    private readonly RequestDelegate _next;

    public CorsMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
        context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
        context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
        if (context.Request.Method == "OPTIONS")
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            await context.Response.WriteAsync(string.Empty);
        }

        await _next(context);
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class CorsMiddlewareExtensions
{
    public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CorsMiddleware>();
    }
}

And the Startup.cs looks like this:

public void ConfigureServices(IServiceCollection services)
{
     services.AddCors();
     services.AddMvc(ConfigureMvcOptions);
     services.AddSwaggerGen(ConfigureSwaggerOptions);
}

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        app.UseMiddleware(typeof(CorsMiddleware));
        app.UseAuthentication();
        app.UseMvc();
 }

Upvotes: 0

Views: 2268

Answers (2)

mojoblanco
mojoblanco

Reputation: 723

Go to your Startup.cs file

In the ConfigureServices method add;

services.AddCors(options =>
{
    options.AddPolicy("AllowLocalhost",
    builder => builder
    .AllowAnyOrigin()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials()
    .SetPreflightMaxAge(TimeSpan.FromDays(5)));
});

Then in the Configure method add;

app.UseCors("AllowLocalhost");

Upvotes: 0

Lee O.
Lee O.

Reputation: 3312

I ran into this exact problem 2 days ago. My solution was to short circuit the pipeline when it's an options request. I don't know what happens in the other middleware but something else is changing the statuscode after you have set it. And really for an options preflight request, you probably don't need anything else to execute anyways.

Change this:

    if (context.Request.Method == "OPTIONS")
    {
        context.Response.StatusCode = (int)HttpStatusCode.OK;
        await context.Response.WriteAsync(string.Empty);
    }

    await _next(context);

to this:

    if (context.Request.Method == "OPTIONS")
    {
        context.Response.StatusCode = (int)HttpStatusCode.OK;
        await context.Response.WriteAsync(string.Empty);
    }
    else
    {
        await _next(context);
    }

Upvotes: 2

Related Questions