如何通过 AngularJs 发送 AntiForgeryToken?
Posted
技术标签:
【中文标题】如何通过 AngularJs 发送 AntiForgeryToken?【英文标题】:How to send AntiForgeryToken via AngularJs? 【发布时间】:2021-11-04 06:49:47 【问题描述】:在我的 MVC 项目中,我通过 AngularJs 调用 method
。我需要将AntiForgeryToken
发送到method
。
在视图中
@using (html.BeginForm())
@Html.AntiForgeryToken()
...
在 MVC 中controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Model model)
...
在 AngularJs 中 controller
this.data.Name= $('#txtNm').val();
this.data.Id = $('#Id').val();
var token = angular.element("input[name='__RequestVerificationToken']").val();
$http(
method: "POST",
url: "/Students/Create",
dataType: 'json',
data: this.data,
headers:
'__RequestVerificationToken': token
).then(function (response)
//success
, function (response)
//error
);
但是,它不起作用。
【问题讨论】:
【参考方案1】:试试这个
this.data.__RequestVerificationToken = $('input[name="`__RequestVerificationToken`"]').val();
.....
data: this.data,
dataType: 'JSON',
contentType:'application/x-www-form-urlencoded; charset=utf-8',
.....
【讨论】:
@SYEDNAWAZPRINCE 对不起,diff net 版本,试试另一个【参考方案2】:1-CSHTML
通过调用 AntiForgery.GetTokens 方法在服务器端生成令牌。
<script>
@functions
public string GetAntiForgeryToken()
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
</script>
@Html.AntiForgeryToken()
<input name="RequestVerificationToken" data-ng-model="RequestVerificationToken" type="hidden" data-ng-init="RequestVerificationToken='@GetAntiForgeryToken()'" />
2-MVC 控制器
当您处理请求时,从请求标头中提取令牌。然后调用 AntiForgery.Validate 方法来验证令牌。如果令牌无效,Validate 方法会引发异常。
对于验证 AntiForgeryToken,我使用了 MyValidateAntiForgeryTokenAttribute()。
[HttpPost]
[MyValidateAntiForgeryTokenAttribute()]
public ActionResult Create()
// Your students create logic will be here
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MyValidateAntiForgeryTokenAttribute : FilterAttribute
private void ValidateRequestHeader(HttpRequestBase request)
string cookieToken = String.Empty;
string formToken = String.Empty;
string tokenValue = request.Headers["__RequestVerificationToken"];
if (!String.IsNullOrEmpty(tokenValue))
string[] tokens = tokenValue.Split(':');
if (tokens.Length == 2)
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
AntiForgery.Validate(cookieToken, formToken);
3-Angular JS 控制器
在 http 调用中,在标头 $scope.RequestVerificationToken 中分配
'__RequestVerificationToken': $scope.RequestVerificationToken
【讨论】:
代码放在哪里?在 mvccontroller
或 AngularJs controller
?
将以上代码放入 Angular js 控制器中。
但function
格式在js
文件中是不允许的
@SYEDNAWAZPRINCE 很抱歉回复晚了。那是我的错误,我没有解释清楚。我已经编辑了我的 cmets 以及所有必需的代码。我希望这对你有用。
@RajshKumarSwain,感谢您的回复。您使用了自定义过滤器MyValidateAntiForgeryTokenAttribute
。但是,我想使用默认的ValidateAntiForgeryToken
。以上是关于如何通过 AngularJs 发送 AntiForgeryToken?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 iOS 上显示从我的 angularjs 应用程序发送的 PDF(Blob)
AngularJS - 如何在所有请求上发送通用 URL 参数?