What is CORS?
CORS stands for cross-origin Resource Sharing and is an HTTP mechanism that allows resource sharing from one domain to another domain. This is a browser with built-in security that checks on every request if it's made on another origin.
First of all, the browser makes a preflight request to check whether the CORS is allowed or not for the current origin. The browser sends a request along with Headers and HTTP methods like GET, POST, PUT, and DELETE; once the preflight response received from the server stating that the CORS is allowed after that browser makes the actual http request as shown in below screenshot.
To illustrate this example, I have to create an Angular 16 project and try to access the .NET 7 Web API weatherforcast endpoint from the Angular app.
When it's trying to access the weatherforcast endpoint, it's throwing a CORS error, as shown below
To fix the CORS issue, will try to allow the CORS for the localhost:4200 origin on which Angular is running.
I will try to add one entry in the Appsettings.json.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedOrigins": [
"http://localhost:4200",
"https://rahulsdotnet.com"
]
}
To enable the CORS, we need to do the below steps.
- Read the allowed origins from the configuration
- Add the AddCors services with the required named policy
var allowedOrigin = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>();
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy("myAppCors", policy =>
{
policy.WithOrigins(allowedOrigin)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
- Add the UseCors middleware with the name
app.UseCors("myAppCors");
Now we are done with enabling the CORS, and let's reload the annular application to fetch the data from web api.
Here we go. Now we are able to fetch the data from the different origin by enabling CORS Origin. In the above, after allowing the CORS, we can see the Access-Control-Allow-Origin header added in the response for the localhost:4200 (Angular app URL).
Summary
In this article, we learn about what is CORS, Pre flight requests (Option Method), and how to enable CORS in .NET 7.
Hope you enjoyed this article. Thanks for reading!!