In the View
<script type="Text/javascript">@functions { Public stringTokenheadervalue () {stringCookietoken,fromtoken; Antiforgery.gettokens (NULL, outCookietoken, outFromtoken); returncookietoken+":"+Fromtoken; }} $function ({... $.ajax ("Api/value", {data:{...}, type:'Post', DataType:'JSON', headers:{'Requestverificationtoken':'@ToKenHeaderValue ()'}, Success:fucntion (data) {...} })})</script>
//self-written filter
1 Public classMyvalidateantiforgerytokenattribute:fileterattribute,iauthorizationfilter2 {3 Private voidValidaterequestheader (httprequestbase request)4 { 5 stringcookietoken="";6 stringfromtoken="";7 stringTokenvalue=request. header["Requestverificationtoken"];8 if(!string. IsNullOrEmpty (tokenvalue))9 {Ten string[] Tokens=tokenvalue.split (':'); One if(Tokens. Length=2) A { -cookietoken=tokens[0]. Trim (); -fromtoken=tokens[1]. Trim (); the } - } - antiforgery.validate (cookietoken,fromtoken); - } +}
public void Onauthiorization (Authorizationcontexte context)
21 {
Try
23 {
if (context. HttpContext.Request.IsAjaxRequest ())//Determine if Ajax commits
25 {
Validaterequetheader (context. HttpContext.Request);
27}
-Else
Antiforgery.validate ();
30}
Catch
32 {
Httpantiforgeryexception throw new ("...");
34}
In the Controller's action
1 [httppost]//indicates post submission
2 [myvalidateantiforgerytoken]//here calls its own write filter to prevent CSRF attacks
3 Public actionresult Value () 4 {5 ..... 6 }
Reference: Preventing Cross-site Request Forgery (CSRF) Attacks