Skip to content

Instantly share code, notes, and snippets.

@pradeepn
Created August 7, 2013 11:20
Show Gist options
  • Save pradeepn/6173210 to your computer and use it in GitHub Desktop.
Save pradeepn/6173210 to your computer and use it in GitHub Desktop.
MVC AntiForgery Token for all jquery post
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
}
}
<!--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