Imagine we are visiting a foreign country. We want to send a package to someone in another country. However, the customs officers at the border won't allow us to send the package unless we have the proper documentation and the destination country has agreed to accept it.
csharp
dotnet add package Microsoft.AspNetCore.Cors
2. Configure Services in Program.cscsharp
builder.Services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("https://localhost:7235");
}
});
3. Apply the CORS policy in the middleware pipeline:csharp
app.UseCors("CorsPolicy");
## Adjusting the CORS Policy
The policy we created is rather strict. You can adjust it as per your requirements. Some of the things you can configure are:csharp
policy.WithOrigins("https://myapp.com", "https://anotherapp.com");
csharp
policy.AllowAnyOrigin();
csharp
policy.WithHeaders("header1", "header2");
csharp
policy.WithMethods("GET", "POST");
Note: Be cautious with allowing all origins (AllowAnyOrigin) as it can expose your API to potential security threats from malicious websites. Always ensure that you understand the security implications of the CORS settings you choose.
## Pre-Flight Requests
When you make a request (e.g., a POST request) that could potentially have side effects, browsers will first send a "pre-flight" request using the OPTIONS method to check if the actual request is allowed. This is done to make sure that the server accepts the request and knows about the origin making it.
For instance, if your client sends a request with a custom header or uses an HTTP method other than GET or HEAD, a pre-flight request is triggered.
In our previous .NET Core CORS setup, pre-flight requests are automatically handled by the middleware because we used .AllowAnyHeader() and .AllowAnyMethod().
## Tightening Security
While it might be tempting to use .AllowAnyOrigin() and .AllowAnyMethod() for simplicity, it's more secure to only enable what's needed:csharp
policy.WithOrigins("https://myapp.com")
.WithMethods("GET", "POST");
csharp
policy.WithOrigins("https://myapp.com")
.WithHeaders("X-Custom-Header", "Authorization");
Note: If you use .AllowCredentials(), you can't use .AllowAnyOrigin() due to security concerns. You need to explicitly specify the origins.
## Exposing Headers
There might be situations where you want your client-side application to have access to certain headers in the CORS response. You can specify which headers should be exposed:
csharp
policy.WithOrigins("https://myapp.com")
.WithExposedHeaders("X-My-Custom-Header");
## Wrapping up
Understanding and managing CORS in .NET Core is crucial when building APIs that are accessed from different origins. By configuring the CORS middleware correctly and securely, you ensure both functionality and security for your web applications. Remember to always review your CORS configuration to minimize potential security risks.
That's all from me today.Stop arguing about code style. In this course you get a production-proven setup with analyzers, CI quality gates, and architecture tests — the exact system I use in real projects. Join here.
Not sure yet? Grab the free Starter Kit — a drop-in setup with the essentials from Module 01.
Design Patterns that Deliver — Solve real problems with 5 battle-tested patterns (Builder, Decorator, Strategy, Adapter, Mediator) using practical, real-world examples. Trusted by 650+ developers.
Just getting started? Design Patterns Simplified covers 10 essential patterns in a beginner-friendly, 30-page guide for just $9.95.
Every Monday morning, I share 1 actionable tip on C#, .NET & Architecture that you can use right away. Join here.
Join 20,000+ subscribers who mass-improve their .NET skills with actionable tips on C#, Software Architecture & Best Practices.
Subscribe to the TheCodeMan.net and be among the 20,000+ subscribers gaining practical tips and resources to enhance your .NET expertise.