GET and POST to same Controller Action in ASP.NET MVC

后端 未结 3 1200
北海茫月
北海茫月 2020-12-25 09:30

I\'d like to have a single action respond to both Gets as well as Posts. I tried the following

[HttpGet]
[HttpPost]
public ActionResult SignIn()


        
相关标签:
3条回答
  • 2020-12-25 09:52
    [HttpGet]
    public ActionResult SignIn()
    {
    }
    
    [HttpPost]
    public ActionResult SignIn(FormCollection form)
    {
    }
    
    0 讨论(0)
  • 2020-12-25 10:00

    This is possible using the AcceptVerbs attribute. Its a bit more verbose but more flexible.

    [AcceptVerbs(HttpVerbs.Get|HttpVerbs.Post)]
    public ActionResult SignIn()
    {
    }
    

    More on msdn.

    0 讨论(0)
  • 2020-12-25 10:01

    Actions respond to both GETs and POSTs by default, so you don't have to specify anything:

    public ActionResult SignIn()
    {
        //how'd we get here?
        string method = HttpContext.Request.HttpMethod;
        return View();
    }
    

    Depending on your need you could still perform different logic depending on the HttpMethod by operating on the HttpContext.Request.HttpMethod value.

    0 讨论(0)
提交回复
热议问题