CodexBloom - Programming Q&A Platform

Visual Studio 2022 - how to to Debug a .NET 6 Web API with Swagger and CORS Issues

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
csharp aspnet-core swagger cors visual-studio C#

I'm working with a frustrating scenario when trying to debug my .NET 6 Web API project in Visual Studio 2022. I have integrated Swagger for API documentation and set up CORS to allow requests from localhost:3000 (where my React app runs). However, when I start the debugging session, I get a CORS behavior in the browser console stating: `Access to XMLHttpRequest at 'http://localhost:5000/api/values' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I've added the following CORS configuration in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/behavior"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` I've verified that Swagger is set up correctly, and I can see the API documentation loading properly. The API responds correctly when accessed directly via Postman. I also confirmed that the CORS middleware is registered before the endpoints are mapped. Despite these configurations, the CORS behavior continues. I've tried cleaning and rebuilding the solution, restarting Visual Studio, and even disabling and re-enabling CORS, but nothing has worked. Is there something I might have overlooked or misconfigured? Any suggestions would be greatly appreciated!