在我的MVC项目中,我调用了AngularJs的method。我需要向method发送AntiForgeryToken。
在视图中
@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
});但是,它不起作用。
发布于 2021-09-07 11:41:30
尝尝这个
this.data.__RequestVerificationToken = $('input[name="`__RequestVerificationToken`"]').val();
.....
data: this.data,
dataType: 'JSON',
contentType:'application/x-www-form-urlencoded; charset=utf-8',
.....发布于 2021-09-07 14:18:50
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-角度JS控制器
在标题$scope.RequestVerificationToken中指定的http调用中
'__RequestVerificationToken': $scope.RequestVerificationToken
}https://stackoverflow.com/questions/69087094
复制相似问题