Enable OPTIONS header for CORS on .NET Core Web API
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();
}
How to enable cors in ASP.NET Core 6.0 Web API project?
The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.
fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))
Results in the following response:
How to enable CORS in ASP.net Core WebAPI
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).
If you haven't already, install the CORS nuget package.
Install-Package Microsoft.AspNetCore.Cors
In the ConfigureServices method of your startup.cs, add the CORS services.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Then in your Configure method of your startup.cs, add the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.
Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/
How to enable CORS in ASP.NET Core
For ASP.NET Core 6:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
See the official docs for more samples.
For ASP.NET Core 3.1 and 5.0:
You have to configure a CORS policy at application startup in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
The CorsPolicyBuilder
in builder
allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
[EnableCors("MyPolicy")]
Or apply it to every request:
public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
// ...
// This should always be called last to ensure that
// middleware is registered in the correct order.
app.UseMvc();
}
Related Topics
How to Implement an Exhaustmap Handler in Rx.Net
How to Create an Instance of an Arbitrary Array Type at Runtime
For I = 0, Why Is (I += I++) Equal to 0
Split String, Convert Tolist<Int>() in One Line
How to Check If Any Flags of a Flag Combination Are Set
Displayname Attribute VS Display Attribute
Create an Application Setup in Visual Studio 2013
Regex: C# Extract Text Within Double Quotes
Convert from SQLdatareader to JSON
Copy Object to Object (With Automapper )
How to Mock the New Httpclientfactory in .Net Core 2.1 Using Moq
Unable to Set Row Visible False of a Datagridview
Alternate Property Name While Deserializing