Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vadim-kovalyov/680c279c93b54d97ebb9 to your computer and use it in GitHub Desktop.
Save vadim-kovalyov/680c279c93b54d97ebb9 to your computer and use it in GitHub Desktop.
How to set ValidateAntiForgeryToken Attribute globaly
public class AntiForgeryTokenFilterProvider : IFilterProvider
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
IEnumerable<FilterAttribute> filters = actionDescriptor.GetFilterAttributes(true);
bool disableAntiForgery = filters.Any(f => f is DisableAntiForgeryCheckAttribute);
string method = controllerContext.HttpContext.Request.HttpMethod;
if (!disableAntiForgery
&& String.Equals(method, "POST", StringComparison.OrdinalIgnoreCase))
{
yield return new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class DisableAntiForgeryCheckAttribute : FilterAttribute
{
}
// Usage:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//**//
FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider());
//**//
}
}
// Html Helper method
public static class HtmlExtensions
{
public static MvcForm BeginSecureForm(this HtmlHelper html, string action, string controller)
{
var form = html.BeginForm(action, controller);
html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());
return form;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment