Angular 5/ASP.NET Core 2项目配置XSRF时遇HTTP 400错误求助
Hey there! Let's walk through the most common misconfigurations that cause this 400 Bad Request when setting up XSRF between Angular 5 and ASP.NET Core 2. I’ve tackled this exact stack combo before, so here’s what to check step by step:
1. ASP.NET Core 2 Server-Side Checks
Antiforgery Service Configuration
First, double-check your Startup.ConfigureServices setup—this is where most people slip up:
services.AddAntiforgery(options => { options.Cookie.Name = "XSRF-TOKEN"; // Must match what Angular expects options.Cookie.HttpOnly = false; // Critical! Angular needs to read this cookie, so can't set to HttpOnly options.HeaderName = "X-XSRF-TOKEN"; // The header Angular will send back to your API });
The HttpOnly = false setting is a super common mistake—if you leave it as true, Angular can't access the cookie to generate the request header.
Middleware Order Matters
In Startup.Configure, make sure your middleware is ordered correctly. Cookie policy and antiforgery logic need to run before MVC:
// Allow frontend access to non-HttpOnly cookies app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Lax, HttpOnly = HttpOnlyPolicy.None }); app.UseAuthentication(); // Optional: Manually trigger antiforgery cookie generation for GET requests app.Use(next => context => { var antiforgery = context.RequestServices.GetRequiredService<IAntiforgery>(); if (context.Request.Method == "GET") { antiforgery.SetCookieTokenAndHeader(context); } return next(context); }); app.UseMvc();
Validate the Action/Controller
Your POST endpoint needs to enforce XSRF validation. Either add the attribute directly to the action:
[HttpPost] [ValidateAntiForgeryToken] public IActionResult YourPostEndpoint(YourModel model) { // ... logic here }
Or register it globally in ConfigureServices to avoid adding it to every action:
services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
2. Angular 5 Client-Side Checks
HttpClient & XSRF Module Setup
Angular's HttpClientModule handles XSRF automatically, but you need to align the cookie/header names with your server:
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule, HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', // Match server's cookie name headerName: 'X-XSRF-TOKEN' // Match server's expected header name }) ] }) export class AppModule { }
Note: Don't use the old HttpModule—it doesn't handle XSRF the same way as HttpClientModule.
Verify Request Behavior
- Angular only automatically adds the
X-XSRF-TOKENheader to non-GET/HEAD/OPTIONS requests (POST/PUT/DELETE). Make sure your failing call is one of these. - If you're making cross-origin requests, you need to enable credentials:
And your server's CORS policy must allow credentials too (see the next section).this.http.post('/api/your-endpoint', yourData, { withCredentials: true }).subscribe(...);
Debug the Cookie & Header
Open your browser's DevTools:
- Go to Application > Cookies and check if
XSRF-TOKENexists, with the correct domain/path. - Go to Network > Your POST Request and check if the
X-XSRF-TOKENheader is present and matches the cookie value. If it's missing, Angular couldn't read the cookie.
3. Cross-Origin (CORS) Pitfalls
If your Angular app is on a different port/domain than your API, fix these CORS settings:
services.AddCors(options => { options.AddPolicy("AllowAngular", builder => builder.WithOrigins("http://localhost:4200") // Your Angular URL .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials()); // Critical for passing cookies/XSRF headers });
And don't forget to apply the policy in Startup.Configure:
app.UseCors("AllowAngular");
内容的提问来源于stack exchange,提问作者jcmag

