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

前端 未结 4 1159
别那么骄傲
别那么骄傲 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条回答
  •  孤城傲影
    2021-01-01 12:44

    That's not ASP.NET MVC limitation or whatever. It's .NET and how classes work: no matter how hard you try, you cannot have two methods with the same name on the same class which take the same parameters. You could cheat using the [ActionName] attribute:

    [HttpGet]
    [ActionName("Foo")]
    public ActionResult GetMe()
    {
       ...
    }
    
    [HttpPut]
    [ActionName("Foo")]
    public ActionResult PutMe()
    {
       ...
    }
    
    [HttpDelete]
    [ActionName("Foo")]
    public ActionResult DeleteMe()
    {
       ...
    }
    
    [HttpPost]
    [ActionName("Foo")]
    public ActionResult PostMe()
    {
       ...
    }
    

    Of course in a real RESTFul application the different verbs would take different parameters as well, so you will seldom have such situations.

    You may take a look at SimplyRestful for some ideas about how your routes could be organized.

提交回复
热议问题