Search code examples
asp.net-mvchttp-posthttp-getasp.net-mvc-controller

MVC [HttpGet] controller annotation optional?


If I have 2 controller actions:

    [HttpGet]
    public ActionResult Login()
    {
        //...

        return View();
    }

and

    [HttpPost]
    public ActionResult Login(FormCollection values)
    {
        //...

        return RedirectToAction("Index","Home");
    }

It seems that the Post decoration is required for this to work (which makes sense), but the HttpGet decoration is entirely optional. It works fine with or without. It seems that MVC defaults controller actions to HttpGet unless otherwise specified.

I'll have to decided if I want a future reader of my code to have to figure that out on my own or not, or whether I want to have to remember to add HttpGet everywhere for consistency. But my question is not about whether it is a good practice to include the explicit decoration even though it is defaulted that way already.

My question is: is it ALWAYS the case that I don't need to decorate controller methods with HttpGet? Is there some way that this can bite me if I do or do not explicitly specify? I've searched on this a but and all I can find is posts describing why you might want to use both annotations rather than the reason for/against including the HttpGet specifically.


Solution

  • You don't have to specify this explicitly, no. However, please note:

    • Not specifying the verb on an action will mean that the method accepts both GET and POST. If there are two actions, however, the one labelled POST will be used for POST and the other will default for GETs.
    • Applying HttpGet will mean an action accepts only GET requests.
    • Labelling actions as GET can make it more obvious to other developers what your intention is.

    Is there some way that this can bite me if I do or do not explicitly specify?

    Not very likely. I could imagine a situation where something might be showing some strange behaviour or not working as expected because of it, but it'd be rare.