---
title: "Cache CORS Preflight Requests"
description: "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. "
updated: 2025-01-20
tags: [".NET", "CORS"]
canonical: "https://steven-giesel.com/blogPost/5fc7cb62-d5ad-4f07-831c-d6c1c6974641/cache-cors-preflight-requests"
---

# Cache CORS Preflight Requests

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 time<sup>Not all requests. So called "simple" requests are exempted!</sup>.
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:

```csharp
services.AddCors(options =>
{
    options.AddPolicy("AllowAllOrigins",
        builder =>
        {
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetPreflightMaxAge(TimeSpan.FromMinutes(10));
        });
});
```

[`SetPreflightMaxAge`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.cors.infrastructure.corspolicybuilder.setpreflightmaxage?view=aspnetcore-9.0) 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`).