在ASP.Net Core应用程序中使用Angular作为前端框架,可能会遇到在IFRAMES中嵌入Angular组件或页面时,由于Antiforgery令牌不匹配而出现错误的情况。
为了解决这个问题,需要在后端控制器的ActionResult中包含Antiforgery令牌,并在前端Angular组件中注入Antiforgery令牌。
后端代码示例:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task CreateItem(Item item)
{
if (ModelState.IsValid)
{
// process the data
return RedirectToAction("Index");
}
// if the data is invalid, return to the same page with the same Antiforgery token
var token = await _antiforgery.GetAndStoreTokens(HttpContext);
ViewData["AntiForgeryToken"] = token;
return View(item);
}
前端代码示例:
import { Component, Inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-create-item',
templateUrl: './create-item.component.html',
})
export class CreateItemComponent {
public item: Item;
public antiforgeryToken: string;
constructor(
private http: HttpClient,
@Inject(DOCUMENT) private document: Document,
@Inject('BASE_URL') private baseUrl: string,
) {}
ngOnInit() {
// get the Antiforgery token from the hidden input element in the form
this.antiforgeryToken = this.document.getElementsByName('__RequestVerificationToken')[0].getAttribute('value');
}
createItem() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'RequestVerificationToken': this.antiforgeryToken // include the Antiforgery token in the request header
});
this.http.post- (`${this.baseUrl}api/items`, this.item, { headers }).subscribe(result => {
// do something
});
}
}