Loading content...
CORS, or Cross-Origin Resource Sharing, is a crucial security mechanism that enables web applications to request resources from different domains. Learn how to configure CORS in .NET to ensure secure and seamless API integration.
CORS policies control access to your APIs from external sources.
Cross-origin requests enable modern apps to connect across services.
Proper setup of CORS reduces failed preflight and access issues.
Loading content...
Let's discuss your project and create a custom web application that drives your business forward. Get started with a free consultation today.

CORS, or Cross-Origin Resource Sharing, is a crucial security mechanism that enables web applications to request resources from a domain other than their own.
This blog post will explore the concept of CORS, its importance, and the steps to implement it successfully in C# and .NET frameworks.
CORS (Cross-Origin Resource Sharing) is a browser security feature that regulates resource sharing between different domains to enhance security.
If you have a web application hosted onhttp://frontend-app.comthat needs to fetch data from a REST API hosted onhttp://api.backend-server.com, then you’re dealing with different origins (different domains). The browser enforces the Same-Origin Policy, which blocks requests made from one origin to another unless explicitly allowed by the server.
Let’s see an example of a shopping website fetching product data.
You visit https://mystore.com, an online shopping website. The website’s frontend needs to fetch product details, pricing, and inventory from its backend API hosted athttps://api.mystore.com. Since the frontend and backend are on different origins (different subdomains), the browser enforces the Same-Origin Policy and blocks the request unless CORS is properly configured.
When you browse the product page on https://mystore.com, the frontend sends a request to the backend API to fetch product data:
1
2
3
4
5
// Frontend request example
fetch('https://api.mystore.com/products', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
}).then(r => r.json());The browser checks the origin of the request:
Since these origins are different, the browser enforces the Same-Origin Policy and blocks the request, returning a CORS error like this:
1
Access to fetch at 'https://api.mystore.com/products' from origin 'https://mystore.com' has been blocked by CORS policy.The scenario described can be addressed using the following example in .NET Core 8.0.
Make sure the Microsoft.AspNetCore. Cors package is installed (usually included by default in ASP.NET Core)
1
dotnet add package Microsoft.AspNetCore.CorsAdd the CORS policy to allow requests from your frontend origin.
You can configure CORS by calling AddCors in the builder.Services section of your Program.cs file:
1
dotnet add package Microsoft.AspNetCore.Cors1
2
3
4
5
6
7
8
9
// Program.cs (.NET 8)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
policy.WithOrigins("https://mystore.com")
.AllowAnyHeader()
.AllowAnyMethod());
});"AllowSpecificOrigin" is a policy name that can be used in middleware in the subsequent step.
Use the CORS middleware to apply the policy. This configuration can be applied globally across the entire application or tailored to specific endpoints.
1
2
3
// Apply CORS globally
var app = builder.Build();
app.UseCors("AllowSpecificOrigin");We can also Apply the CORS policy to specific controllers or endpoints:
1
2
3
// Apply CORS to a specific endpoint
app.MapGet("/products", () => Results.Ok(new [] { "Item1", "Item2" }))
.RequireCors("AllowSpecificOrigin");You can test the CORS headers using browser developer tools. Make sure the
Access-Control-Allow-Origin header is present in the server's response.
1
Access-Control-Allow-Origin: https://mystore.comCross-Origin Resource Sharing (CORS) utilizes certain HTTP headers to decide if a browser should permit requests from different origins. These headers are crucial for securing cross-origin requests and adhering to the rules set by the server.
1. Access-Control-Allow-Origin: Defines the origins that are allowed to access the resource.
1
Access-Control-Allow-Origin: https://example.comA missing or incorrect header results in the browser blocking the request.
Restricts access to trusted origins, preventing unauthorized cross-origin requests.
2. Access-Control-Allow-Methods : The HTTP methods permitted for cross-origin requests include GET, POST, and HEAD.
1
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONSMake sure that the client is only able to carry out actions that are allowed on the resource.
3. Access-Control-Allow-Headers : Defines the HTTP headers that may be utilized within a request.
1
Access-Control-Allow-Headers: Content-Type, Authorization, X-Custom-Header4 . Access-Control-Expose-Headers : Response header specifies which headers are accessible to the browser in the response to a cross-origin request.
By default, browsers limit access to sensitive headers such as ‘Content-Length’ or custom headers.
This header allows clients to read specified headers, enhancing data access control.
5. Access-Control-Max-Age : The duration for which a browser can cache the results of a preflight request is specified by the `Access-Control-Max-Age` header. This value is set in seconds and dictates how long the preflight response is valid before a new preflight request must be made.
1
Access-Control-Max-Age: 3600Minimizing repetitive preflight requests enhances performance.
6. Access-Control-Allow-Credentials: Indicates whether cookies or credentials can be sent in cross-origin requests.
1
Access-Control-Allow-Credentials: trueThe Access-Control-Allow-Credentials header is crucial for enabling credentials like cookies, authorization headers, or TLS client certificates in cross-origin requests. It needs to be set to ‘true’ to activate this feature.
Tight Coupling with Access-Control-Allow-Origin, Access-Control-Allow-Credentials: true cannot be used with a wildcard (*) in the Access-Control-Allow-Origin header.
If misconfigured, credentials might be exposed to unauthorized origins, leading to security vulnerabilities like session hijacking or cross-site scripting (XSS).
CORS is used to overcome the same-origin policy enforced by web browsers, which restricts web pages from making requests to a domain other than the one that served the web page. Here’s why CORS is essential:
CORS should be enabled in scenarios such as:
There are many examples with different architectures.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Example dynamic CORS (simplified)
app.Use(async (context, next) =>
{
var origin = context.Request.Headers["Origin"].ToString();
var allowed = new[] { "https://mystore.com", "https://admin.mystore.com" };
if (!string.IsNullOrEmpty(origin) && allowed.Contains(origin))
{
context.Response.Headers["Access-Control-Allow-Origin"] = origin;
context.Response.Headers["Vary"] = "Origin";
context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
}
await next();
});You can configure “AllowedOrigins” within the appsettings.json file. as below example.
1
2
3
4
5
6
7
8
9
// appsettings.json
{
"Cors": {
"AllowedOrigins": [
"https://mystore.com",
"https://admin.mystore.com"
]
}
}Add a section in your appsettings.json to define the allowed origins and other CORS settings. Now, load the CORS settings from appsettings.json in Program.cs
1
2
3
4
5
6
// Program.cs - load from configuration
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
builder.Services.AddCors(o => o.AddPolicy("AllowSpecificOrigin",
p => p.WithOrigins(allowedOrigins)
.AllowAnyHeader()
.AllowAnyMethod()));The approach mentioned offers benefits such as centralized configuration and environment-specific configurations.
CORS plays a crucial role in today’s web development, facilitating secure interactions across various domains, which is particularly vital for APIs and handling cross-origin requests. By incorporating CORS into .NET, developers can guarantee smooth communication for Single Page Applications, external integrations, and backend services.