ASP.NetCoreAntiforgery,Angular和IFRAMES
创始人
2024-09-17 18:30:34
0次

在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
    });
  }
}

相关内容

热门资讯

专业讨论!wepoker模拟器... wepoker模拟器哪个好用AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏...
重大消息!wpk有那种辅助吗,... 重大消息!wpk有那种辅助吗,WPK有挂吗教程(先前有开挂)AI 智能体黑科技再上新,自动化能力开挂...
推荐几款新版!wepoker底... 您好:wepoker底牌透视这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
总算了解!wpk有作弊吗,德普... 总算了解!wpk有作弊吗,德普之星外卦神器软件教程(竟然有开挂)AI 智能体黑科技再上新,自动化能力...
大神推荐!wepoker透视脚... wepoker透视脚本免费AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻...
避坑细节!如何下载德普之星辅助... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
一分钟了解!!wepoker辅... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
玩家科普!wpk真的有透视嘛,... 玩家科普!wpk真的有透视嘛,WPK透视脚本工具(好像存在有辅助挂)AI 智能体黑科技再上新,自动化...
一分钟揭秘!德普之星辅助工具如... 您好:德普之星辅助工具如何打开这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
大家学习交流!wepoker游... 您好:wepoker游戏安装教程这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...