简体   繁体   中英

asp.net Core MVC 2 - configure CORS to accept NULL origin

I need to configure a web api implemented using asp.net core 2.2 to accept a "null" origin ('Origin' header missing or empty).

Before you jump down my throat: I know that having a null origin is bad. But there's unfortunately nothing I can do about it, because the call is made by a third party server that passes a null origin and I have no control over it, so I need to make my api accept a null origin.

I tried doing this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHsts();
    app.UseMvc();
    app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
}

...

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    //Configuring CORS
    services.AddCors();
}

but it doesn't make any difference. When I make a POST request (using jQuery's ajax method), I get the following error:

在此处输入图片说明

I have the suspicion that a null/missing origin is just discarded before even checking it... am I right? Is there any way to accept a null origin?

The CORS middleware must be placed before the MVC middleware, or the MVC middleware (and your controller) will send the response without allowing the CORS middleware a chance to run.

Change your configure method to this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHsts();
    app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
    app.UseMvc(); // Add this middleware last.
}

The order of AddMvc and AddCors in the ConfigureServices method does not matter.

Ok, I solved it. The problem was very simple: the UseCors() and AddCors() methods in the Startup class must be called BEFORE the UseMvc() and AddMvc() methods.

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