Enabling CORS in ASP - NET Core by Example - Code Maze Blog
Enabling CORS in ASP - NET Core by Example - Code Maze Blog
🔥
SEARCH
Enabling CORS in
ASP.NET Core
Posted by Code Maze | Updated Date Oct 8, 2021 | 24
What Is CORS?
Let’s learn what the term same-origin actually means first.
What Is the Same-Origin policy?
The Same-origin policy states that a Web browser will only
allow communication between two URLs if they belong to the
same origin. That is, the client app ( https://example.com )
cannot communicate with the server app
( https://example.net ) as they belong to a different origin.
This policy exists to isolate potentially malicious scripts from
harming other documents on the web.
Thank you, your sign-up request
All modern browsers set the Origin header automatically, successful! Please check your em
which indicates the domain of the site is making the request. to confirm.
Preflight Requests
Sometimes, instead of a simple GET request, a client may need
to send requests like PUT, DELETE, etc. For such requests, the
browser sends an additional request (an OPTIONS request)
called a Preflight request. This is done just before the actual
request to make sure that the original request succeeds. If it
does, the browser sends the actual request.
A preflight request
Actual request
Creating an Application
Without CORS
In the demo, let’s create two projects. The first one is going to
be a Web API project, and the second one is going to be a
Blazor WebAssembly project.
Let’s create a Web API project that will be our server. Once we
create this project, we are going to modify the launchSettings.
json file:
{
"profiles": {
"CorsServerApp": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": false,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:5001;http
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
As you can see, this app will run on the https://localhost:5001
URI.
{
"profiles": {
"CorsClientApp": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{
"applicationUrl": "https://localhost:5011;http
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Okay. We have both a client and the server app running and
they belong to different origins. The server app will run on port
5001 and the client app on port 5011.
await builder.Build().RunAsync();
}
Here, we just set up the base address for the HttpClient, which
is the URI of our Web API.
@code {
private WeatherForecast[] forecasts;
...
}
So, we can see that the request is blocked by CORS policy and
our client app is not allowed to fetch the data from the
required resource.
services.AddControllers();
}
public void Configure(IApplicationBuilder app, I
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(_policyName);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
We can agree that this policy is not the strict one, but it is a
basic setup that will remove the CORS issue for our client
application.
services.AddCors(opt =>
{
opt.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
As you can see, we are not providing the name for the policy.
Additionally, we don’t have to provide the policy name in the
UseCors method:
app.UseRouting();
app.UseCors();
app.UseAuthorization();
For the rest of the article, we are going to stick with the
named CORS policy configuration.
services.AddControllers();
}
app.UseRouting();
app.UseCors();
This time, we are not specifying the policy name since we are
using more than one policy in our application.
[EnableCors("CorsPolicy")]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => ne
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Lengt
})
.ToArray();
}
[EnableCors("AnotherCorsPolicy")]
[HttpGet("anotherPolicyExample")]
public IActionResult GetTempAboveLimit()
{
return Ok("This action is protected with another
}
As you can see for the first action, we are enabling CORS
using the old named policy – CorsPolicy. But for the other
action, we are using a new policy – AnotherCorsPolicy.
So, let’s see how we can configure different policy options and
make sense of using different named policies in our
application.
Right now, for both policies, we are allowing any origin, any
header, and any method. But let’s say, we want to allow only
our client application to access the first GET action from the
WeatherForecast controller, and some other client (on port
5021) to access the second action:
public void ConfigureServices(IServiceCollection ser
{
services.AddCors(opt =>
{
opt.AddPolicy(name: _policyName, builder =>
{
builder.WithOrigins("https://localhost:5
.AllowAnyHeader()
.AllowAnyMethod();
});
opt.AddPolicy(name: _anotherPolicy, builder
{
builder.WithOrigins("https://localhost:5
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
}
By using the
SetIsOriginAllowedToAllowWildcardSubdomains method,
we allow origins to match a configured wildcard domain when
evaluating if the origin is allowed.
services.AddControllers();
}
});
.WithMethods("GET");
Additionally, when we want to expose some headers, we can
use the WithExposedHeaders method. For example, in our
Blazor WebAssembly Pagination with ASP.NET Core Web
API article, we create a pagination functionality on the Web
API’s side and add the required information inside the X-
Pagination header:
[HttpGet]
public async Task<IActionResult> Get([FromQuery] Pro
{
var products = await _repo.GetProducts(productPa
Response.Headers.Add("X-Pagination", JsonConvert
return Ok(products);
}
And that’s it for our CORS configuration.
Additional read: You can see the CORS in action with .NET Core
and Angular projects by reading the .NET Core tutorial.
How to Disable CORS
Finally, a small note on disabling CORS. Sometimes we need
to disable CORS on the action or the controller level.
[DisableCors]
[HttpGet]
public async Task<IActionResult> Get([FromQuery] Pro
{
var products = await _repo.GetProducts(productPa
Response.Headers.Add("X-Pagination", JsonConvert
return Ok(products);
}
Conclusion
Think of CORS as a relaxation attempt to the more restrictive
Same-Origin policy. On one side, there is a growing need for
security on the web. And on the other, there is a need to
integrate web services. CORS provides rich tools for our need
for an open and secure web, and ASP.NET Core allows us to
take advantage of CORS in our cross-platform web
applications.
Subscribe Login
J oin the discussion
{} [+]
24 COMMENTS Oldest
View Comments
© Copyright code-maze.com 2016 - 2022