Home >Backend Development >C++ >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
method in the Startup
class: ConfigureServices
IServiceCollection.AddCors
<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
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
<code class="language-csharp">[EnableCors("MyCorsPolicy")] public class MyController : Controller { // ... }</code>method:
Configure
UseCors
This 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!