CORS
Cross-Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing (CORS) is a security mechanism that allows or denies requests made from a different domain than the resource's origin. It is implemented in web APIs to ensure secure cross-domain communication
How to Implement CORS in a Web API
Implementation methods vary depending on the API framework or platform used.
1. In ASP.NET Core Web API
ASP.NET Core provides built-in support for managing CORS using middleware and attributes.
note : Origion, Port, similar protocal like https
Global Policy (Configuration): You define a policy in Program.cs (or Startup.cs) and apply it globally.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// 1. Define the policy name and allowed origins
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("https://www.example.com") // Specify the allowed client URL
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// ... other services
var app = builder.Build();
// 2. Enable the middleware
app.UseCors("AllowSpecificOrigin");
// ... other middleware and routing
app.Run();
Controller/Action Level: Apply the policy using attributes on controllers or specific action methods.
[ApiController]
[Route("[controller]")]
[EnableCors("AllowSpecificOrigin")] // Apply the defined policy
public class WeatherForecastController : ControllerBase
{
// ... controller methods
}
Comments
Post a Comment