Created
August 7, 2013 11:20
-
-
Save pradeepn/6173210 to your computer and use it in GitHub Desktop.
MVC AntiForgery Token for all jquery post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FilterConfig | |
{ | |
public static void RegisterGlobalFilters(GlobalFilterCollection filters) | |
{ | |
filters.Add(new HandleErrorAttribute()); | |
filters.Add(new GlobalValidateAntiForgeryToken()); | |
//Instead of putting [ValidateAntiForgeryToken] Use this for all request | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!--Layout/Master Page--> | |
<form id="__AjaxAntiForgeryForm" action="#" method="post">@Html.AntiForgeryToken()</form> | |
<script type="text/javascript"> | |
//Method-1 | |
var addAntiForgeryToken = function (data) { | |
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(); | |
return data; | |
} | |
//Method-1 Implementation | |
$.ajax({ | |
url: url, | |
data: addAntiForgeryToken(data), | |
. | |
. | |
. | |
}); | |
//Method-2 | |
var addGlobalAntiForgeryToken = function(){ | |
$.ajaxSetup({ | |
data: { | |
__RequestVerificationToken: $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val() | |
} | |
}); | |
} | |
//Method-2 Implementation | |
$(document).ready(function(){ | |
addGlobalAntiForgeryToken();//Now all $.ajax will have anti forgery token | |
}); | |
</script> | |
<!-- for mvc based post use this inside the form --> | |
<form> | |
@Html.@Html.AntiForgeryToken() | |
<input type="submit" value="Save"/> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment