CodexBloom - Programming Q&A Platform

ASP.NET Core 6.0: how to to configure CORS for specific subdomain on API

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

I've been working on this all day and I'm trying to configure I can't seem to get I'm attempting to set up I'm working on a personal project and I'm working on an ASP.NET Core 6.0 Web API that needs to allow CORS requests only from a specific subdomain, but I'm running into issues getting it to work as expected... I've set up CORS in my `Startup.cs` file like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowSubdomain", builder => { builder.WithOrigins("https://sub.example.com") .AllowAnyMethod() .AllowAnyHeader(); }); }); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("AllowSubdomain"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` However, when I make a request from the specified subdomain, I'm still getting a CORS behavior in the browser: ``` Access to fetch at 'https://api.example.com/resource' from origin 'https://sub.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` I've double-checked that the request is indeed coming from `https://sub.example.com`, and I've also tried adding `.AllowCredentials()` but that didn't resolve the scenario either. Additionally, I've ensured that the API is being served over HTTPS. I've also tested removing the specific `WithOrigins` method and used `AllowAnyOrigin()` temporarily to confirm that CORS is being configured correctly, and in that case, it worked fine. This leads me to believe there's something off with my subdomain setup. Is there something I'm missing in the CORS configuration, or is there another aspect I need to consider for the subdomain setup to work correctly? Any ideas what could be causing this? I'm coming from a different tech stack and learning C#. Am I missing something obvious? Am I missing something obvious? I'm on Windows 11 using the latest version of C#. Any ideas how to fix this?