본문 바로가기

Backend/.NET

.NET - CORS

반응형

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.

Browser Access Denied

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

Returned Data on the Browser

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

 

728x90
반응형