Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS for any port on localhost

in asp.net core i can use middleware to enable CORS on certain methods as described here

i want to know if its possible to enable CORS for any scheme and any port on localhost ( for testing purpose only). i tried wildcard and it does not work

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        if(_environment.IsDevelopment())
        {
              options.AddDefaultPolicy(
                 builder =>
                 {
                     builder.WithOrigins("http://localhost/*",
                                         "https://localhost/*");
                 });
             });
        }
        else
        {
            options.AddDefaultPolicy(
                 builder =>
                 {
                     builder.WithOrigins("http://example.com",
                                         "http://www.contoso.com");
                  });
             });
        }

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
like image 617
LP13 Avatar asked Aug 16 '19 20:08

LP13


1 Answers

ASP.NET Core's SetIsOriginAllowed method gives you full control over whether or not an origin is allowed to participate in CORS. Here's an example based on your code sample:

if(_environment.IsDevelopment())
{
    options.AddDefaultPolicy(builder =>
    {
        builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
    });
}
else
{
    // ...
}

The origin value passed in to the SetIsOriginAllowed delegate is the full origin, which looks something like http://localhost:8080. Using Uri, the code above compares the Host against localhost, which ends up allowing all localhost origins.

like image 148
Kirk Larkin Avatar answered Sep 22 '22 02:09

Kirk Larkin