简体   繁体   中英

Add 'access-control-allow-origin' response to options preflight request in Asp.NET

I'm getting the following error in Chrome:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:9000 ' is therefore not allowed access.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseIISPlatformHandler();

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseCors(policy => policy
       .WithOrigins("http://localhost:9000")
       .AllowAnyMethod()
       .WithHeaders("Access-Control-Allow-Origin, Content-Type, x-xsrf-token, Authorization")
       .AllowCredentials());

    app.UseMvc();
}

According to chrome there is not a single header being added to the response.

What is the correct way to add the access-control-allow-origin header to a options response in Asp.NET 5?

Consider that Google Chrome has an issue which does not support localhost to go through the Access-Control-Allow-Origin .

In your code, you have enabled CORS with the AddCors and UseCors methods in Configure method, please make sure you've followed the instructions available in Specifying a CORS Policy ( which is used in ConfigureServices method ) and How to enable CORS in ASP.NET 5

You can also simply write an Action Filter for plain Asp.net MVC controller .

Types of CORS'

  1. Microsoft.AspNet.WebApi.Cors : use it to enable the CORS request ONLY for the Web APIs.
  2. Microsoft.AspNet.Cors : Use it to enable CORS for MVC controllers.
  3. Microsoft.Owin.Cors : Use it to enable CORS for all cross-origins requests coming to your site, for example, when you you want to enable CORS for both Web API and SignalR.

这真的没有意义,但正如@Sirwan 建议的那样,使用.AllowAnyHeader()设置对选项响应的访问...

为了克服预检问题,在您的 API 中添加与[httpoption]相同的名称方法并从那里返回成功,现在只需运行您的网络/客户端应用程序,您将在第一次 httpoption 方法命中时两次命中相同的方法,然后是您的原始方法

将其放在startup.cs文件的配置部分:

app.UseCors (x => x.AllowAnyOrigin ().AllowAnyMethod ().AllowAnyHeader ());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM