Cache CORS Preflight Requests

1/20/2025
2 minute read

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).

Lifetime Scope in Blazor Client and Server Apps

You probably are well aware of the Lifetime Scope for ASP.NET Core website. There are basically 3 scopes: Transient, Scoped and Singleton. Let's have a look how they differ in Blazor Client and Server.

Blazor with CancellationToken support

What happens when a user navigates away and still has a pending request to our server? Or what happens if we have a request which might take forever and wastes our resources?

Let's tackle these problems with a CancellationToken.

Blazor Client - Loading Screen

If you are using Blazor WebAssembly aka client-side Blazor you are faced with an issue: The .NET runtime including your assemblies has to be downloaded first. We are taking about some megabytes as the initial load.

Depending on the connection of your client there is a time where basically nothing happens. The default template just has a simple "Loading..." text. So let's change that.

An error has occurred. This application may no longer respond until reloaded. Reload x