简体   繁体   中英

How to correctly enable CORS for a subdomain in an ASP.NET Core 2.2 project?

I am trying to serve my assets on a subdomain instated of the same domain. So when my main domain is https://localhost:44111/ the assets URL would be something like https://assets.localhost:44111/css/style.css

The style.css file makes a request to include a custom font my_custom_font.eot like so

@font-face {
    ....
    src: url('/css/fonts/my_custom_font.eot?123');
}

When I include the style.css file which is located on the assets subdomain, I get the following error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource athttps://assets.localhost:44111/css/fonts/my_custom_font.eot?123 . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

To make sure I am clear, both style.css and my_custom_font.eot are located on the same domain assets.localhost:44111 . The request to include style.css works with no issues. But, when style.css makes a request to include the my_custom_font.eot the request is prohibited.

I tried to follow the documentation to enable CORS. I added the following code to the Startup.ConfigureServices(IServiceCollection services) method

services.AddCors(options =>
{
    options.AddPolicy("AllowSubDomainTraffic",
    builder =>
    {
        builder.WithOrigins("https://assets.localhost:44111")
               .AllowAnyHeader()
               .AllowAnyMethod();
    });
});

Then in the Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) method I added the following

app.UseCors("AllowSubDomainTraffic");

However, I am still receiving the CORS header 'Access-Control-Allow-Origin' missing error in the console of the browser.

This is how I respond to the subdomains in my app

app.MapWhen(context => {
    return context.Request.Host.Value.StartsWith("assets.", StringComparison.OrdinalIgnoreCase)
} (appBuilder) =>
{
    appBuilder.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider("C:/assets"),
    });
});

How can I correctly enable CORS for a subdomain?

WithOrigins(string[]) takes an param of strings (array of string, string[]). This allows you to do:

builder.WithOrigins("https://localhost:44111", "https://assets.localhost:44111")
  .AllowAnyHeader()
  .AllowAnyMethod();

note: don't forget that cors urls cannot end in /

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