在我的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({
方法。"POST"。
網址。"/Students/Create"。
dataType。'json'。
data: this.data。
headers: {
'__RequestVerificationToken': token
}
}).then(function (response) {
//成功。
}, function (response) {
//error
但是,它不作業。
uj5u.com熱心網友回復:
試試這個
span class="hljs-keyword">this.data. __RequestVerificationToken = $('input[name="`__RequestVerificationToken"]').val()。
.....
data: this.data,
dataType。'JSON'。
contentType:'application/x-www-form-urlencoded; charset=utf-8'。
.....
uj5u.com熱心網友回復:
1-CSHTML
令牌是通過呼叫AntiForgery.GetTokens方法在服務器上生成的。
<script>
@functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken ":"/span> formToken。
}
}
</script>
@Html.AntiForgeryToken()
< input name="RequestVerificationToken" data-ng-model="RequestVerificationToken" type="hidden" data-ng-init="RequestVerificationToken='@GetAntiForgeryToken()'" />
2-MVC控制器
當你處理請求時,從請求頭中提取令牌。然后呼叫AntiForgery.Validate方法來驗證這些令牌。如果令牌無效,Validate方法會拋出一個例外。對于Validate AntiForgeryToken,我使用了MyValidateAntiForgeryTokenAttribute()。
[HttpPost]
[MyValidateAntiForgeryTokenAttribute()]
public ActionResult Create()
{
//你的學生創建邏輯將在這里。
}
[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"/span>]。
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 Controller
在http呼叫中,將$scope.RequestVerificationToken分配到頭中
。 '__RequestVerificationToken': $scope.RequestVerificationToken
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/307477.html
標籤:
下一篇:如何將單選按鈕改為div?
