如何根据接受的HTTP谓词重载ASP.NET MVC操作?

Met*_*uru 23 asp.net-mvc action overloading http-verbs

想要为基于REST的API使用相同的URL进行GET/PUT/DELETE/POST,但是当关于Actions的唯一不同之处是它接受哪个HTTP谓词时,它认为它们是重复的!

"Type已经定义了一个名为'Index'的成员,它具有相同的参数类型."

我说的是什么呢?这个只接受GET,这个只接受POST ...应该可以共存吗?

怎么样?

Dar*_*rov 35

这不是ASP.NET MVC限制或其他.它是.NET以及类如何工作:无论你怎么努力,你都不能在同一个类中使用相同名称的两个具有相同名称的方法.你可以使用[ActionName]属性作弊:

[HttpGet]
[ActionName("Foo")]
public ActionResult GetMe()
{
   ...
}

[HttpPut]
[ActionName("Foo")]
public ActionResult PutMe()
{
   ...
}

[HttpDelete]
[ActionName("Foo")]
public ActionResult DeleteMe()
{
   ...
}

[HttpPost]
[ActionName("Foo")]
public ActionResult PostMe()
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

当然,在真正的RESTFul应用程序中,不同的动词也会采用不同的参数,因此您很少会遇到这种情况.

您可以查看SimplyRestful,了解有关如何组织路线的一些想法.


Tho*_*hom 8

虽然ASP.NET MVC允许您使用相同名称的两个操作,但.NET不允许您使用相同签名的两个方法 - 即相同的名称和参数.

您将需要以不同的方式命名方法使用该ActionName属性告诉ASP.NET MVC它们实际上是相同的操作.

也就是说,如果你在谈论a GET和a POST,这个问题很可能就会消失,因为这个POST动作会占用更多的参数GET,因此可以区分.

所以,你需要:

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}
Run Code Online (Sandbox Code Playgroud)

要么:

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost]
public ActionResult ActionName(string aParameter) {...}
Run Code Online (Sandbox Code Playgroud)