Skip to content

Latest commit

 

History

History
130 lines (107 loc) · 2.75 KB

README.md

File metadata and controls

130 lines (107 loc) · 2.75 KB

NuGet NuGet

Cors Policy Settings

How to use (Sample)

Default

In appsettings.json

{
  "CORSPolicies": [
    {
      "Name": "Test",
      "Methods": [ "GET", "POST" ],
      "Origins": [ "http://www.example.com" ]
    },
    {
      "Name": "AllowAll",
      "Headers": ["*"],
      "Methods": ["*"],
      "Origins":  ["*"] 
    }
  ]
}

Note: See CorsPolicy documentation to see which properties to use

Startup.cs

public void ConfigureServices(IServiceCollection services)
{    
    //Replaces the use of services.AddCors()
    services.AddCorsPolicies(Configuration);
    
    /// ...

    // Add framework services.
    services.AddMvc();

    /// ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{   
    if (env.IsDevelopment())
    {
        app.UseCors("AllowAll");
    }
    else
    {
        app.UseCors("Test");
    }

    /// ...

    app.UseMvc();
}

Custom

In any json settings file (example: cors.json)

{
  "Policies": [
    {
      "Name": "Test",
      "Methods": [ "GET", "POST" ],
      "Origins": [ "http://www.example.com" ]
    },
    {
      "Name": "AllowAll",
      "Headers": ["*"],
      "Methods": ["*"],
      "Origins":  ["*"] 
    }
  ]
}

Startup.cs

Add you json file to the configuration builder.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddJsonFile("cors.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

Define the section where the policies should be read.

public void ConfigureServices(IServiceCollection services)
{    
    //Replaces the use of services.AddCors()
    services.AddCorsPolicies(Configuration.GetSection("Policies"));
    
    /// ...

    // Add framework services.
    services.AddMvc();

    /// ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{   
    if (env.IsDevelopment())
    {
        app.UseCors("AllowAll");
    }
    else
    {
        app.UseCors("Test");
    }

    /// ...

    app.UseMvc();
}