How can I overload ASP.NET MVC Actions based on the accepted HTTP verbs?

前端 未结 4 1188
别那么骄傲
别那么骄傲 2021-01-01 12:14

Wanted to use the same URL for a GET/PUT/DELETE/POST for a REST based API, but when the only thing different about the Actions is which HTTP verbs it accepts, it considers t

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 12:35

    While ASP.NET MVC will allow you to have two actions with the same name, .NET won't allow you to have two methods with the same signature - i.e. the same name and parameters.

    You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.

    That said, if you're talking about a GET and a POST, this problem will likely go away, as the POST action will take more parameters than the GET and therefore be distinguishable.

    So, you need either:

    [HttpGet]
    public ActionResult ActionName() {...}
    
    [HttpPost, ActionName("ActionName")]
    public ActionResult ActionNamePost() {...}
    

    Or:

    [HttpGet]
    public ActionResult ActionName() {...}
    
    [HttpPost]
    public ActionResult ActionName(string aParameter) {...}
    

提交回复
热议问题