Almost all applications are using CORS (Cross-Origin Resource Sharing) to allow the client to access the resources from the server. When the client sends a request to the server, the server will respond with the Access-Control-Allow-Origin header to allow the client to access the resources.
When is CORS is used?
CORS is used when the client and server are in different domains. For example, if the client is running on http://localhost:3000
and the server is running on http://localhost:5000
, then the client needs to send a CORS request to the server to access the resources. To do that the client will send a preflight request to the server to check if the server allows the client to access the resources. This can be seen as OPTIONS request in the browser developer tools. If this is valid, another request will be sent to the server to get the resources.
As REST APIs are stateless, the server needs to validate the request (and every request) every timeNot all requests. So called "simple" requests are exempted!.
But we can instruct (via the Access-Control-Max-Age
header) that this doesn't have to be done all the time. In .NET this can be easily configured inside the AddCors
method:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetPreflightMaxAge(TimeSpan.FromMinutes(10));
});
});
SetPreflightMaxAge
will instruct the client to cache the CORS preflight request for 10 minutes (so it sends the Access-Control-Max-Age
header with the value 600
).