angularjs - 如何通过 AngularJs 发送 AntiForgeryToken?
问题描述
在我的 MVC 项目中,我method
由 AngularJs 调用。我需要发送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-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
}
推荐阅读
- javascript - 如何使用 jQuery 添加事件监听器?
- c# - 实现自己的 KeyValuePair 版本的问题
- python - 将excel数据转换为嵌套字典和列表
- javascript - Access-Control-Allow-Origin 不是 * 但 Chrome 坚持是(升级 apollo-server 后)
- c++ - OpenGL:在着色器中执行 TexCoord 计算,不好的做法?
- javascript - 1 到 150 之间的有效字符串的正则表达式,用逗号和连字符分隔
- path - Game Maker 2 换房间时路径中断
- java - Java Json Jackson 在没有 getter 和 setter 的情况下保存私有字段
- javascript - Suitescript 1:删除添加的订单项时出错
- android-studio - 构建 - 使模块/项目使用错误的构建类型