CodexBloom - Programming Q&A Platform

How to configure CORS for an ASP.NET Core Web API with custom headers?

👀 Views: 70 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
asp.net-core cors web-api C#

I'm trying to configure I've searched everywhere and can't find a clear answer. I'm working with an ASP.NET Core 6 Web API, and I need to enable CORS to allow requests from a specific front-end application that uses some custom headers. However, I keep working with an behavior saying `CORS request did not succeed`. I've already added the CORS services in my `Startup.cs` file like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => { builder.WithOrigins("https://myfrontend.com") .WithHeaders("Content-Type", "Authorization") .AllowAnyMethod(); }); }); services.AddControllers(); } ``` In the `Configure` method, I have: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseCors("AllowSpecificOrigin"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` Despite this configuration, I'm still getting the CORS behavior when trying to make a fetch call from my front-end application: ```javascript fetch('https://myapi.com/api/values', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer mytoken' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(behavior => console.behavior('behavior:', behavior)); ``` I've checked the network tab and it shows that the preflight OPTIONS request is failing. I've also ensured that there are no typos in the origin URL. Is there something I'm missing in the CORS configuration? Any help would be appreciated! Has anyone dealt with something similar? I'm developing on macOS with C#. Any examples would be super helpful. I'm working on a microservice that needs to handle this. What's the best practice here?