45

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);
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
LP13
  • 30,567
  • 53
  • 217
  • 400

2 Answers2

81

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.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
  • 6
    I also needed to add `.AllowAnyHeader()` and `.AllowAnyMethod()` to the builder policy on my Web API. – Brian Reading Jan 28 '21 at 00:02
  • 11
    You can also use `new Uri(origin).IsLoopback` instead of checking `new Uri(origin).Host == "localhost"`. – Mr. X May 05 '21 at 07:45
  • Is there a way to use this in conjunction with `.WithOrigins()`? When I've tried, `.SetIsOriginAllowed()` overrides any other origins I've specified beforehand and only allows ones that match the conditional. – Harrison Paine Jun 17 '21 at 13:05
  • 2
    @HarrisonPaine You can't combine those two methods, but you can do anything you like inside of `SetIsOriginAllowed`, which could `||` with something like `YourOrigins.Contains(origin, StringComparer.Ordinal)`. – Kirk Larkin Jun 17 '21 at 13:39
  • @KirkLarkin sure, but [the documentation](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.withorigins?view=aspnetcore-5.0#Microsoft_AspNetCore_Cors_Infrastructure_CorsPolicyBuilder_WithOrigins_System_String___) for `.WithOrigins()` mentions "This method normalizes the origin value prior to adding it to Origins to match the normalization performed by the browser on the value sent in the ORIGIN header." which makes me think it's doing more than a simple comparison. – Harrison Paine Jun 29 '21 at 00:45
  • 3
    @HarrisonPaine Here's the [source](https://github.com/dotnet/aspnetcore/blob/release/5.0/src/Middleware/CORS/src/Infrastructure/CorsPolicyBuilder.cs#L55-L97) to show exactly what `WithOrigins` is doing for you. – Kirk Larkin Jun 29 '21 at 08:10
  • @KirkLarkin Where is `_environment` and `options` is coming from? Is it from the Builder? Can you add this to your explanation? – Tamb Jul 16 '22 at 15:57
  • `_environment` is available as `builder.Environment` – Eric J. Sep 27 '22 at 19:26
  • @Tamb, https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-3.1#inject-iwebhostenvironment-into-the-startup-class explains where `_environment` comes from, except it uses `_env`. `options` is just using the name LP13 used in his example code. – Mike Grove aka Theophilus Mar 16 '23 at 21:46
-4

I'm currently using this for testing and it works, if you take the wildcard off yours should work.

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

        services.AddMvc();

        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://localhost");
            });
        });



        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
   }
James
  • 11
  • 3