CodexBloom - Programming Q&A Platform

ASP.NET Core 6: solution with Configuring CORS for Blazor WebAssembly App

👀 Views: 50 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-02
asp.net-core blazor cors C#

I'm relatively new to this, so bear with me. I'm currently working on an ASP.NET Core 6 Web API that needs to serve a Blazor WebAssembly client. I've configured CORS to allow traffic from my client app, but I'm working with a persistent scenario where requests from the Blazor app are being blocked. The behavior in the browser console states: ``` Access to XMLHttpRequest at 'https://localhost:5001/api/data' from origin 'https://localhost:5002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. ``` In my `Startup.cs`, I have the following configuration: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowBlazorApp", builder => builder .WithOrigins("https://localhost:5002") .AllowAnyHeader() .AllowAnyMethod()); }); services.AddControllers(); } 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("AllowBlazorApp"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` I've verified that the Blazor app runs on `https://localhost:5002` and I'm calling the API at `https://localhost:5001/api/data`. I've also ensured that the API is running before I make requests. When I inspect the network calls, it seems the preflight OPTIONS request is being sent, but it isn't returning a successful status. I also attempted to add `WithExposedHeaders()` to the CORS policy, but it didn't change the outcome. I'm not seeing any issues in the API logs that would indicate that the request is even reaching the server. I've tried restarting both applications and clearing the browser cache, but the behavior continues. Is there any additional step I might have missed in setting up CORS for my Blazor WebAssembly app? Any help or guidance would be greatly appreciated! What am I doing wrong?