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

标签 c# asp.net .net asp.net-mvc asp.net-web-api

似乎 ASP.NET 隐式地将名为 GetXPostX 的方法分别解释为 GET 和 POST 方法,因为它们的名称以 HTTP 方法名称为前缀。 PUT 和 DELETE 也是如此。

不幸的是,我有一个名为 Delete 的方法,但我希望它被解释为 POST,因此我使用 [HttpPost] 属性明确指定它是一个 POST。这有效,只要它没有在接口(interface)内声明...

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].
    }
}

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

最佳答案

接口(interface)属性的属性不会继承到类,您可以将接口(interface)设为抽象类。

Microsoft找到答案:

The product team does not want to implement this feature, for two main reasons:

  • Consistency with DataAnnotations.Validator
  • Consistency with validation behavior in ASP.Net MVC
  • tricky scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute would take precedence?

来源:Attribute on Interface members does not work

关于c# - 如何阻止 ASP.NET Web API 隐式解释 HTTP 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916148/

相关文章:

c# - 数据库中的 Entity Framework 生成命名空间错误

使用基于表单的 Asp.net MVC 身份验证与基于 Windows 的身份验证

c# - 具有后台 worker 的 Web 应用程序的 Nhibernate session 管理策略?

c# - WPF AppDomain UnhandledException 处理程序超时

.net - Netduino no "Console.WriteLine",控制台在当前上下文中不存在

c# - 创建表达式以使用 out 参数调用方法

c# - 在 IIS7 中从 ASP.NET 调用非托管代码

C# : Passing a Generic Object

c# - 通过ASP.Net网站下载文件

c# 动态创建的标签大小不够宽