{"id":11920,"date":"2025-01-30T06:32:23","date_gmt":"2025-01-30T06:32:23","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=11920"},"modified":"2025-01-30T06:33:59","modified_gmt":"2025-01-30T06:33:59","slug":"enable-cors-in-aspnet-core","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/dot-net\/enable-cors-in-aspnet-core","title":{"rendered":"How to Enable CORS in ASP.NET Core"},"content":{"rendered":"<h2>What is CORS?<\/h2>\n<p>CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict how resources on a web page can be requested from another domain. By enabling CORS, you allow your ASP.NET Core Web API to accept requests from specific origins or domains.<\/p>\n<h2>How to Configure CORS in ASP.NET Core?<\/h2>\n<p>CORS can be configured in three simple steps:<\/p>\n<h3>Step 1: Add the CORS Services in Startup.cs<\/h3>\n<p>In the ConfigureServices method, add the CORS services and define a policy using AddCors:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\r\npublic void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddControllers();\r\n\r\n    \/\/ Add CORS services and define a policy\r\n    services.AddCors(options =&gt;\r\n    {\r\n        options.AddPolicy(\"AllowSpecificOrigins\", builder =&gt;\r\n        {\r\n            builder.WithOrigins(\"https:\/\/example.com\", \"https:\/\/another-example.com\") \/\/ Allowed origins\r\n                   .AllowAnyHeader() \/\/ Allow any header\r\n                   .AllowAnyMethod(); \/\/ Allow any method (GET, POST, etc.)\r\n        });\r\n\r\n        options.AddPolicy(\"AllowAllOrigins\", builder =&gt;\r\n        {\r\n            builder.AllowAnyOrigin()\r\n                   .AllowAnyHeader()\r\n                   .AllowAnyMethod();\r\n        });\r\n    });\r\n}\r\n<\/pre>\n<h3>Step 2: Use CORS Middleware in the Pipeline<\/h3>\n<p>In the Configure method, apply the CORS middleware:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\r\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\r\n{\r\n    if (env.IsDevelopment())\r\n    {\r\n        app.UseDeveloperExceptionPage();\r\n    }\r\n\r\n    app.UseRouting();\r\n\r\n    \/\/ Use the CORS middleware\r\n    app.UseCors(\"AllowSpecificOrigins\"); \/\/ Use the specified policy\r\n\r\n    app.UseAuthorization();\r\n\r\n    app.UseEndpoints(endpoints =>\r\n    {\r\n        endpoints.MapControllers();\r\n    });\r\n}\r\n<\/pre>\n<h3>Step 3: Apply CORS Policies at the Controller or Action Level<\/h3>\n<p>You can apply CORS at the controller or action level using the [EnableCors] attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">\r\n[ApiController]\r\n[Route(\"api\/[controller]\")]\r\n[EnableCors(\"AllowSpecificOrigins\")] \/\/ Apply a specific CORS policy\r\npublic class ExampleController : ControllerBase\r\n{\r\n    [HttpGet]\r\n    public IActionResult Get()\r\n    {\r\n        return Ok(\"CORS is enabled for specific origins.\");\r\n    }\r\n}\r\n\r\nTo disable CORS for a specific action, use the [DisableCors] attribute:\r\n[HttpGet]\r\n[DisableCors]\r\npublic IActionResult GetWithoutCors()\r\n{\r\n    return Ok(\"CORS is disabled for this action.\");\r\n}\r\n<\/pre>\n<h2>Points to Remember<\/h2>\n<ol>\n<li>Define CORS policies in AddCors.<\/li>\n<li>Use CORS middleware in Configure.<\/li>\n<li>Apply CORS globally, at the controller level, or at the action level.<\/li>\n<li>Use AllowCredentials carefully to avoid security risks.<\/li>\n<\/ol>\n<p>By following these steps, you can enable and configure CORS in your ASP.NET Core Web API.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is CORS? CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict how resources on a web page can be requested from another domain. By enabling CORS, you allow your ASP.NET Core Web API to accept requests from specific origins or domains. How to Configure CORS in ASP.NET Core? CORS [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":11921,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[20],"tags":[],"class_list":["post-11920","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dot-net"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11920"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=11920"}],"version-history":[{"count":2,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11920\/revisions"}],"predecessor-version":[{"id":11923,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11920\/revisions\/11923"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/11921"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=11920"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=11920"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=11920"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}