Home >Backend Development >C++ >How to Configure Cross-Origin Resource Sharing (CORS) in ASP.NET Core?

How to Configure Cross-Origin Resource Sharing (CORS) in ASP.NET Core?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 01:56:10226browse

How to Configure Cross-Origin Resource Sharing (CORS) in ASP.NET Core?

Cross-Origin Resource Sharing (CORS) configuration in ASP.NET Core

Cross-origin resource sharing (CORS) in ASP.NET Core is a security feature that allows your web applications to make requests for resources from different sources (such as different domains, protocols, or ports). To enable CORS, you need to configure a CORS policy.

Create CORS policy

The

attribute in ASP.NET Core accepts a EnableCors parameter that specifies the name of the CORS policy to apply. The policy name is simply a string identifier that you can use later to reference the policy. policyName

To create a CORS policy, you can use the

method in the Startup class: ConfigureServices IServiceCollection.AddCors

In this example, a CORS policy called "MyCorsPolicy" is created. This policy allows HTTP methods and headers from two specific sources ("
<code class="language-csharp">public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyCorsPolicy", builder =>
        {
            builder.WithOrigins("http://example.com", "https://www.contoso.com")
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });
}</code>
https://www.php.cn/link/8be904ad045c578053fc6052578f9324

Apply CORS policy

Once you create a CORS policy, you can apply it to specific controllers, actions, or your entire application. To apply it to a single controller, use the attribute:

[EnableCors]To apply the policy to every request, add the

middleware to the application pipeline in the
<code class="language-csharp">[EnableCors("MyCorsPolicy")]
public class MyController : Controller
{
    // ...
}</code>
method:

Configure UseCorsThis will ensure that all requests to the application are subject to the "MyCorsPolicy" policy.

The above is the detailed content of How to Configure Cross-Origin Resource Sharing (CORS) in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn