asp.net-web-api - Web API - 支持的动词吗?

标签 asp.net-web-api asp.net-web-api-routing

我正在为本地代码训练营组织一次演讲,并试图了解 ApiController 中 HTTP 动词的细微差别。关于 ApiController 的一些事情在 Beta、RC 和最终版本之间发生了显着变化,并且关于如何设置它的建议是相互冲突的,有时甚至是错误的。

假设我只是在 WebApiConfig 中保留标准路由:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

(因为如果你在这里添加 {action} 参数,你真的可以把事情放在他们的头上)

我了解该约定如何适用于简单的 Crud 调用,例如:

    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }


    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
    }

或者您可以更改它们,只要它们以动词名称开头即可:

    // GET api/values/5
    public string GetMyStuff(int id)
    {
        return "value";
    }

但是,最初的规范表明 ApiController 支持 Get、Put、Post 和 Delete。 但我可以添加方法:

    public void HeadOfTheClass()
    {
    }

这适用于中心词动词,但我无法为晦涩或不存在的动词添加方法:

    public void MKCOL()
    {
    }
    public void Bubba()
    {
    }

原生“支持”动词的完整列表是什么?

但是,我可以使用 AcceptVerb 属性添加对这些方法的支持:

    [AcceptVerbs("MKCOL")] 
    public void MKCOL()
    {
    }
    [AcceptVerbs("Bubba")]
    public void Bubba()
    {
    }

这也有效,或者对于任何“已定义”动词,请使用 Http 属性:

    [HttpHead]
    public void HeadOfTheClass()
    {
    }

   [HttpGet]
    public void Bubba()
    {
    }

哪个是正确的或首选的? (还有 [GET] 和 [POST] 等属性,这些属性已弃用吗?)

[HttpBindNever] 和 [NonAction] 等效吗?

最佳答案

我喜欢开源。 :)

来自 ReflectedHttpActionDescriptor:

private static readonly HttpMethod[] _supportedHttpMethodsByConvention = 
    { 
        HttpMethod.Get, 
        HttpMethod.Post, 
        HttpMethod.Put, 
        HttpMethod.Delete, 
        HttpMethod.Head, 
        HttpMethod.Options, 
        new HttpMethod("PATCH") 
    };

关于asp.net-web-api - Web API - 支持的动词吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594023/

相关文章:

c# - 具有 WebAPI OData 属性路由的 $Metadata 不工作

.net - 用于扩展 azure 服务总线的 Websocket

c# - 如何使用 ASP.NET Web API 提取并验证授权 header 中的 SAML token ?

angularjs - Angular $resource 和自托管 WebAPI 的 CORS 问题

c# - 在 ApiController 上执行 POST 时处理发送的 id 的最佳实践?

c# - HTTP 代码 405(不允许的方法),当我在 ASP.NET WebAPI CORS 中发送 POST 数据时

c# - 按区域划分的 Controller

c# - Web API 路由操作

c# - 不同的 RoutePrefix,相同的 Controller 名称

c# - 路由上的约束条目 'httpMethod' 必须具有字符串值