
For safety reasons, browsers, by default, do not allow access to servers with different domains. However, when in development this feature can be a pain in the ass. In this writing, we will see how we can negate this feature by adding allowing CORS option to the header of a request.

Implementation
Adding the Service
Go to the Program.cs file, add the Cors service as shown below
builder.Services.AddCors(opt => {
opt.AddPolicy("Cors", policy => {
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("frontAddress");
});
});

Adding the Middleware
Go to the Program.cs file, add a middleware that uses the Cors service we set above. This must come after the service and before the 'app.UseAuthorization();' clause.
app.UseCors("Cors");

Run
Move to the API folder
cd /API
And run the app
dotnet watch


In this writing, we have seen what the cors is and how to disable the feature to allow the browser to access the server.
References
Enable Cross-Origin Requests (CORS) in ASP.NET Core | Microsoft Learn
Enable Cross-Origin Requests (CORS) in ASP.NET Core
Learn how CORS as a standard for allowing or rejecting cross-origin requests in an ASP.NET Core app.
learn.microsoft.com
'Backend > .NET' 카테고리의 다른 글
Project Structure and Optimizing Development Environment (0) | 2023.05.07 |
---|---|
Packages - Identity (0) | 2023.05.01 |
Generic Repository Specification Pattern - Adding Searching (0) | 2023.04.25 |
Generic Repository Specification Pattern - Adding Pagination (0) | 2023.04.24 |
Generic Repository Specification Pattern - Adding Filtering (0) | 2023.04.24 |