Skip to content

Instantly share code, notes, and snippets.

@asssis
Created February 9, 2021 21:10
Show Gist options
  • Save asssis/914eb0a3899e5a6963198df158334377 to your computer and use it in GitHub Desktop.
Save asssis/914eb0a3899e5a6963198df158334377 to your computer and use it in GitHub Desktop.
cors dot.net
[Route("api/[controller]")]
[ApiController]
public class WidgetController : ControllerBase
{
// GET api/values
[EnableCors("AnotherPolicy")]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "green widget", "red widget" };
}
// GET api/values/5
[EnableCors] // Default policy.
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
switch (id)
{
case 1:
return "green widget";
case 2:
return "red widget";
default:
return NotFound();
}
}
}
public class StartupMultiPolicy
{
public StartupMultiPolicy(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
options.AddPolicy("AnotherPolicy",
builder =>
{
builder.WithOrigins("http://www.contoso.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
options.AddPolicy("AllowHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.WithHeaders(HeaderNames.ContentType, "x-custom-header");
});
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyHeader();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment