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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With