如何阻止ASP.NET Web API隐式解释HTTP方法?

Rud*_*dey 7 .net c# asp.net asp.net-mvc asp.net-web-api

似乎ASP.NET隐式地解释了被命名的方法GetX以及分别PostX作为GET和POST方法,因为它们的名称以HTTP方法名称为前缀.对于PUT和DELETE也是如此.

我遗憾地命名了一个方法,Delete但我希望它被解释为POST,所以我使用该[HttpPost]属性明确指定它是一个POST .这是有效的,只要它没有在界面中声明...

public interface IFooBarController
{
    [HttpPost]
    void DoSomething();

    [HttpPost]
    void Delete(int id);
}

public class FooBarController : IFooBarController
{
    public void DoSomething()
    {
       // This API method can only be called using POST,
       // as you would expect from the interface.
    }

    public void Delete(int id)
    {
        // This API method can only be called using DELETE,
        // even though the interface specifies [HttpPost].
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何解决这个问题,而不必为每个实现指定HttpPostAttribute?

Cod*_*shi 2

正如其他人所说,属性不是继承的。由于界面中的属性,DoSomething 不会使用 POST 调用,而是因为这是默认值。在界面中将其更改为 GET,您仍然会注意到 POST 调用它。

您可以在“操作选择”部分中详细了解如何执行操作选择。(第 3 项回答了您关于为什么使用 POST 调用 DoSomething 的问题)