Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable OPTIONS header for CORS on .NET Core Web API

I solved this problem after not finding the solution on Stackoverflow, so I am sharing my problem here and the solution in an answer.

After enabling a cross domain policy in my .NET Core Web Api application with AddCors, it still does not work from browsers. This is because browsers, including Chrome and Firefox, will first send an OPTIONS request and my application just responds with 204 No Content.

like image 894
Niels Brinch Avatar asked Feb 13 '17 08:02

Niels Brinch


People also ask

How do I add a CORS header in .NET core?

Set the allowed request headersAddCors(options => { options. AddPolicy(name: MyAllowSpecificOrigins, policy => { policy. WithOrigins("https://*.example.com") . AllowAnyHeader(); }); }); builder.

How do I enable CORS policy in Web API?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.

What is CORS in .NET core Web API?

The full name of CORS is Cross Origin Resource Sharing. It is a W3C standard that allows a server to make cross-domain calls from the specified domains, while rejecting others By default due to browser security it prevents a web page from making one domain Ajax request to another domain.


2 Answers

Add a middleware class to your project to handle the OPTIONS verb.

using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Hosting;  namespace Web.Middlewares {     public class OptionsMiddleware     {         private readonly RequestDelegate _next;          public OptionsMiddleware(RequestDelegate next)         {             _next = next;         }          public Task Invoke(HttpContext context)         {             return BeginInvoke(context);         }          private Task BeginInvoke(HttpContext context)         {             if (context.Request.Method == "OPTIONS")             {                 context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });                 context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });                 context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });                 context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });                 context.Response.StatusCode = 200;                 return context.Response.WriteAsync("OK");             }              return _next.Invoke(context);         }     }      public static class OptionsMiddlewareExtensions     {         public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)         {             return builder.UseMiddleware<OptionsMiddleware>();         }     } } 

Then add app.UseOptions(); this as the first line in Startup.cs in the Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {     app.UseOptions(); } 
like image 130
Niels Brinch Avatar answered Sep 27 '22 21:09

Niels Brinch


I know it has been answered. Just answering with the updated information. So it would help others.

It is now built into the ASP.NET Core framework.

Just follow https://docs.microsoft.com/en-us/aspnet/core/security/cors

and replace

    app.UseCors(builder =>    builder.WithOrigins("http://example.com")); 

with

        app.UseCors(builder =>        builder.WithOrigins("http://example.com")               .AllowAnyHeader()               .AllowAnyMethod()               .AllowCredentials()); 
like image 24
Jeyara Avatar answered Sep 27 '22 20:09

Jeyara