在Angular 6中使用.Net Core 2时,如果XSRF令牌在发送回API时为空,可能是由于未正确配置Angular的HttpInterceptor所致。以下是一个解决方法的代码示例:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class XsrfInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const xsrfToken = localStorage.getItem('xsrfToken'); // 从本地存储中获取XSRF令牌
if (xsrfToken) {
req = req.clone({
headers: req.headers.set('X-XSRF-TOKEN', xsrfToken) // 将XSRF令牌添加到请求头中
});
}
return next.handle(req);
}
}
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { XsrfInterceptor } from './xsrf.interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: XsrfInterceptor, multi: true } // 提供XsrfInterceptor
]
})
export class AppModule { }
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN"; // 设置XSRF令牌的请求头名称
options.Cookie.Name = "XSRF-TOKEN"; // 设置XSRF令牌的Cookie名称
options.Cookie.HttpOnly = false; // 允许客户端JavaScript访问Cookie
});
通过以上步骤,你的Angular应用程序将会在发送请求时自动添加XSRF令牌到请求头中,并与你的.Net Core 2 API进行验证。确保在登录或获取XSRF令牌时将其存储在本地,以便在每个请求中使用。