How to use CORS in ASP.NET Core minimal APIs
ASP.NET Core offers a simplified hosting model, called minimal APIs, that allows us to build lightweight APIs with minimal dependencies. Although minimal APIs don’t use controllers, and require only minimal code and minimal configuration, they nevertheless allow us to implement advanced features and important security mechanisms such as Cross-Origin Resource Sharing, or CORS.
In this post, we’ll examine how we can work with CORS in minimal APIs in ASP.NET Core. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.
Create an ASP.NET Core Web API project in Visual Studio 2022
To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below.
- Launch the Visual Studio 2022 IDE.
- Click on “Create new project.”
- In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
- Click “Next.”
- In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
- Click “Next.”
- In the “Additional Information” window shown next, select “.NET 9.0 (Standard Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project.
- Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
- Click “Create.”
We’ll use this ASP.NET Core Web API project to work with CORS in the code examples given in the sections below.
What is CORS and why do we care?
An origin of an HTTP request comprises a scheme, a host, and a port number. Any two HTTP requests are from the same origin if they have the same scheme, host, and port number. If any of these differ, then the HTTP requests are cross-origin, i.e., they do not belong to the same origin.
Web browsers have used the same-origin policy for many years. The same-origin policy disallows web pages or scripts loaded from one origin from making HTTP requests to a different origin. While this policy stops malicious scripts from infecting your computer, it also prevents legitimate HTTP requests from executing.
CORS is a W3C standard that allows you to get around the default same-origin policy adopted by the browsers. In short, you can use CORS to allow some cross-origin requests while preventing others. You can leverage the CORS middleware in ASP.NET Core to bypass the security restrictions of the web browser and allow cross-origin requests.
How does CORS work?
Here is a step-by-step discussion on how CORS works.
- A web browser in origin A makes a preflight request using the
Access-Control-Request-Method
andAccess-Control-Request-Headers
(optional) headers to a web server in origin B. - The web browser adds an
Origin
header to the HTTP request. - The web server checks the
Origin
header against the defined policies. - If the request is allowed, the web server sends
Access-Control-Allow-Origin
,Access-Control-Allow-Credentials
(optional), andAccess-Control-Expose-Headers
(optional) headers back to the web browser, specifying the necessary permissions. - The web browser checks for the
Access-Control-Allow-Origin
header in the server’s HTTP response. - If access to origin B is allowed, the web browser proceeds to access the resource.
- If access to origin B is disallowed, the web browser terminates the request.
Let us understand this with an example. Assume that a client application hosted at https://myclientapp.com sends a cross-origin POST request to a server hosted at https://myserverapp.com, and that the request includes the necessary credentials. The header for this HTTP request is shown below.
POST /resource HTTP/1.1
Host: api.myserverapp.com
Origin: https://myclientapp.com
Content-Type: application/json
X-Auth-Token: jk1@3
Below is the header for the response from the server.
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://myclientapp.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: X-Custom-Header
Content-Length: 285
As you can see in the preceding headers, the web server allows the client app running at https://myclientapp.com to send credentials and access the resource.
The following are typical examples of CORS headers:
Access-Control-Allow-Origin: https://myexampledomain.com
Access-Control-Allow-Methods: POST, GET
It should be noted that the web server will not return an error if the request is not allowed. Instead, it is the responsibility of the client to block the request to thwart unauthorized access and return the appropriate error.
Understand the key CORS headers
Here are some of the key CORS headers and their purpose at a glance:
Access-Control-Allow-Origin
: Used to specify which origins are allowed.Access-Control-Allow-Methods
: Used to specify which HTTP methods are allowed.Access-Control-Allow-Headers
: Used to specify which custom headers are allowed to be sent in the HTTP request.Access-Control-Allow-Credentials
: Used to specify whether the web browser should send cookies and HTTP authentication credentials as part of the cross-origin request.
Configure CORS in Program.cs
The following piece of code shows how you can configure CORS in your Program.cs file.
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
{
policy.WithOrigins("https://example-origin.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
Use WithOrigins to define restrictive policies
The WithOrigins
method allows us to define restrictive policies. For example, we could use WithOrigins
to allow access only to specific origins as shown in the following code snippet.
builder.Services.AddCors(options =>
{
options.AddPolicy("MyCustomPolicy", policy =>
policy.WithOrigins("https://joydipkanjilal.com")
.AllowAnyHeader()
.AllowAnyMethod());
});
Configure CORS to allow cross-origin requests
The following code snippet shows how you can register the CORS middleware in Program.cs and configure it to allow cross-origin requests.
app.UseCors("AllowSpecificOrigin");
app.UseCors("AllowAll");
Define a CORS-enabled minimal API endpoint
Once you’ve registered CORS in the Program.cs file, you can define a CORS-enabled minimal API endpoint at a global level as shown in the code snippet given below.
app.MapGet("/api/test", () =>
{
return Results.Ok(new
{ Message = "This is a CORS-enabled endpoint." });
});
Configure CORS for a specific endpoint
You can also configure CORS for a particular endpoint, for example to allow access as shown in the code snippet given below.
app.MapGet("/accessallowed", () => "Access to this endpoint is allowed."). RequireCors ("AllowAll");
The following piece of code shows how you can restrict access to a specific endpoint to a specific origin only in the Program.cs file.
app.MapGet("/accessrestricted", () => "Access to this endpoint is restricted."). RequireCors ("AllowSpecificOrigin");
Configure CORS before authentication
Finally, note that you must configure CORS before adding authentication middleware in the Program.cs file of your ASP.NET Core application. This is illustrated in the code snippet below.
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
Key takeaways
Whether your client or server components are in the same origin or in different origins, CORS is a great way to ensure that your ASP.NET Core minimal API endpoints remain secure and accessible. Most importantly, when using minimal APIs, you can implement CORS in your ASP.NET Core applications with minimal effort and zero boilerplate code.
Original Link:https://www.infoworld.com/article/4069660/how-to-use-cors-in-asp-net-core-minimal-apis.html
Originally Posted: Thu, 09 Oct 2025 09:00:00 +0000
What do you think?
It is nice to know your opinion. Leave a comment.