© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
22 replies
hellounlimited

anti forgery token asp global asax file

hi all, currently i try to implement the anti forgery token following microsoft article (the csrf and ajax section).
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

so if i make a post request to my form, the anti forgery token will be send from my javascript file to asp controller.

here's the implementation i did :
 public class CustomAntiForgery : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            var httpContext = filterContext.HttpContext;
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
        }
    }
 public class CustomAntiForgery : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            var httpContext = filterContext.HttpContext;
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
        }
    }


my controller :
        [HttpPost] 
        [CustomAntiForgery]
        public ActionResult AddMemo{ //...}
        [HttpPost] 
        [CustomAntiForgery]
        public ActionResult AddMemo{ //...}



to enable the anti csrf token by default in global asax file, do we need to add CustomAntiForgery into the Application_Start() method?

so it looks like this

        [CustomAntiForgery]
        protected void Application_Start()
        { //... }
        [CustomAntiForgery]
        protected void Application_Start()
        { //... }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Asp.net (.net461, global.asax)
C#CC# / help
15mo ago
❔ Error about anti-forgery on production when try hit api endpoint
C#CC# / help
3y ago
File upload ASP .net 6
C#CC# / help
3y ago
asp net cshtml javascript file
C#CC# / help
4y ago