如何根据接受的 HTTP 动词重载 ASP.NET MVC 操作?
希望对基于 REST 的 API 的 GET/PUT/DELETE/POST 使用相同的 URL,但是当操作的唯一不同之处在于它接受哪些 HTTP 动词时,它认为它们是重复的!
“Type 已经定义了一个名为‘Index’的成员,具有相同的参数类型。”
我说过了,那又怎样?这个只接受GET,这个只接受POST……应该可以共存吧?
如何?
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 them to be duplicate!
"Type already defines a member called 'Index' with the same parameter types."
To which I said, so what? This one only accepts GET, this one only accepts POST... should be able to be co-exist right?
How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是 ASP.NET MVC 限制或其他什么。这就是 .NET 以及类的工作方式:无论您如何努力,在同一个类上都不可能有两个具有相同名称且采用相同参数的方法。您可以使用
[ActionName]
属性:
当然,在真正的 RESTFul 应用程序中,不同的动词也会采用不同的参数,因此很少会遇到这种情况。
您可以查看 SimplyRestful,了解有关如何组织路线的一些想法。
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: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.
虽然 ASP.NET MVC 允许您拥有两个具有相同名称的操作,但 .NET 不允许您拥有两个具有相同签名的方法 - 即相同的名称和参数。
您需要使用
ActionName
属性以不同的方式命名这些方法,以告诉 ASP.NET MVC 它们实际上是相同的操作。也就是说,如果您正在谈论
GET
和POST
,这个问题可能会消失,因为POST
操作将花费更多时间参数比GET
更容易区分。因此,您需要:
或者:
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 aPOST
, this problem will likely go away, as thePOST
action will take more parameters than theGET
and therefore be distinguishable.So, you need either:
Or:
另一种选择是使用一个方法来接受所有并区分 HttpMethod 并从那里调用适当的代码。例如
Another option is to have a single method that accepts all and distinguishes between HttpMethod and calls the appropriate code from there. E.g.
作为一种解决方法,您可以向其中一个方法添加一个具有默认值的额外参数,只是为了绕过限制并能够构建。
当然,请记住,这不是最推荐的做事方式,而且您还必须在代码中(通过参数名称或通过注释)明确这是一个额外的参数,只是为了允许它构建,当然,请确保您正确地装饰了您的属性。
As a workaround you can add to one of the methods an extra argument with a default value, just to bypass the limitation and be able to build.
Of course take in mind that this is not the most recommended way of doing things, and also you will have to make clear in your code (by the parameter name or via comments) that this is an extra argument just to allow it to build, and of course make sure that you have decorated your attributes correctly.