Solving Cross-Domain Request Issues with CORS in ASP.NET Core Web API
Cross-Origin Resource Sharing (CORS) is crucial for web applications with separately hosted front-end and back-end components. This guide addresses a common CORS configuration problem in ASP.NET Core Web APIs, particularly when deploying to the Azure Free Plan.
The Challenge:
A client website hosted on a different domain experienced CORS restrictions when attempting to access a Web API. Standard Microsoft guidance didn't fully resolve the issue for all API endpoints.
The Solution: A Streamlined CORS Configuration
The solution involves a simplified CORS setup:
Install the Necessary Package: Begin by installing the CORS NuGet package:
<code class="language-bash">Install-Package Microsoft.AspNetCore.Cors</code>
Configure CORS in Startup.cs
: Add the CORS service within the ConfigureServices
method:
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }</code>
Enable CORS in the Configure
Method: Use the UseCors
middleware to enable CORS in the Configure
method. This example allows requests from http://example.com
:
<code class="language-csharp">public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCors(options => options.WithOrigins("http://example.com").AllowAnyMethod()); app.UseMvc(); }</code>
Important Considerations:
"http://example.com"
with your actual client domain.AllowAnyMethod()
grants access to all HTTP methods. For enhanced security, specify allowed methods explicitly.The above is the detailed content of How to Enable CORS in ASP.NET Core Web API for Cross-Domain Requests, Especially on Azure Free Plan?. For more information, please follow other related articles on the PHP Chinese website!