ASP.NET Core中POST请求遇CORS拦截问题的解决咨询
Hey there! Let's break down why your POST request is still hitting that CORS error, even after you configured a policy in Startup.cs. I spot two key issues in your current code:
1. Wrong UseCors Placement & Duplicate Calls
In your Configure method, you’re calling UseCors() twice, and the order is off. CORS middleware needs to run after routing but before authorization to properly intercept incoming requests. Your current setup has a stray UseCors() before UseAuthorization, then another policy-specific call after it—this breaks how the policy gets applied.
2. CORS Policy Doesn’t Allow POST Methods/Headers
Your existing policy only lists allowed origins, but by default, CORS doesn’t permit all HTTP methods (like POST) or custom request headers. That’s why GET might work (if it’s a "simple" request) but POST fails.
Here’s the Fixed Startup.cs Code
First, update the CORS policy to explicitly allow the methods and headers your POST request needs:
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://localhost:YOUR_REAL_PORT", "https://localhost:ANOTHER_REAL_PORT") .AllowAnyMethod() // Grants access to all HTTP methods (GET, POST, PUT, etc.) .AllowAnyHeader(); // Allows custom request headers (like Content-Type for JSON) // Uncomment below if your request sends credentials (cookies, auth tokens) // .AllowCredentials(); }); }); services.AddControllers(); services.AddRazorPages(); }
Then fix the middleware order in Configure—remove the duplicate UseCors() and place the policy call in the correct spot:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, GameUserContext db) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } db.Database.EnsureCreated(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); // Critical: Place UseCors HERE, after UseRouting and before UseAuthorization app.UseCors(MyAllowSpecificOrigins); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); }); }
Quick Double-Checks
- Replace
YOUR_REAL_PORTwith the actual port number of your frontend app (the placeholder ports likefhfhhfhin your code won’t work). - If your POST request includes credentials (like JWT tokens in headers or cookies), uncomment the
.AllowCredentials()line in the policy. - Make sure your frontend’s origin matches exactly what’s listed in
WithOrigins(including the protocolhttps://orhttp://—no typos allowed!).
内容的提问来源于stack exchange,提问作者Israt Jerin

