Skip to content

ArneD/cors-policies-appsettings

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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();
}

Releases

No releases published

Packages

No packages published