Search code examples
c#asp.net-mvc-5antiforgerytoken

Set ValidateAntiForgeryToken attribute to GET/POST for same action MVC5


My question is very straight forward...

I have an Action which accepts both HttpGet and HttpPost, but I want to set ValidateAntiForgeryToken attribute to the action when the http request is POST, not for HttpGet.

I can find whether the request is GET or POST inside the action, but I need to know before the action called.

    [ValidateAntiForgeryToken]  // Only for HttpPost
    public ActionResult Index() // Allows HttpPost / HttpGet
    {

    }

Is there any possibilities to achieve this without duplicating the action?

Thank you


Solution

  • You could conditionally check the request's HTTP method and manually do the validation yourself:

    if (Request.Method.ToLower() == "post") 
    {
        System.Web.Helpers.AntiForgery.Validate();
    }