Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

c# - ASP.NET 5: Access-Control-Allow-Origin in response

From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):

Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *

Enabling it in Startup:

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddCors();
    services.ConfigureCors(options => 
    {
        options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
    });
    //...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...
    app.UseCors("AllowAll");
    //...
}

The problem is that none of these headers are returned and I get the following error when trying to request from the API:

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' is therefore not allowed access.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    //Add CORS middleware before MVC
    app.UseCors("AllowAll");

    app.UseMvc(...);
}

Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...