具有多个POST和单PUT方法的Web Api控制器

时间:2017-01-10 03:04:34

标签: vb.net asp.net-web-api

根据以下代码,我可以拨打/ api / cards和/ api / cards / list,但现在/ api / cards / 1234567890

WebApiConfig

config.Routes.MapHttpRoute( _
       name:="WithActionAndIdApi", _
       routeTemplate:="api/{controller}/{action}/{id}", _
       defaults:=New With {.id = RouteParameter.Optional} _
   )

    config.Routes.MapHttpRoute( _
        name:="WithIdApi", _
        routeTemplate:="api/{controller}/{id}" _
    )

    config.Routes.MapHttpRoute( _
        name:="DefaultApi", _
        routeTemplate:="api/{controller}", _
        defaults:=New With {.action = "DefaultAction"} _
    )

CardsController

<HttpPost()>
<ActionName("DefaultAction")>
Public Function PostValue(<FromBody()> ByVal value As Card_POST.Card) As HttpResponseMessage

<HttpPost()>
<ActionName("list")>
Public Function PostValue(<FromBody()> ByVal value As Cards_POST.CardList) As HttpResponseMessage

<HttpPut()>
Public Function PutValue(ByVal Id As String, <FromBody()> ByVal value As Card_PUT) As HttpResponseMessage

1 个答案:

答案 0 :(得分:1)

我已经更改了我的配置。转到下面的代码,它能够支持我上面的情况。

config.Routes.MapHttpRoute( _
       name:="DefaultApiWithId", _
       routeTemplate:="api/{controller}/{id}", _
       defaults:=New With {.id = RouteParameter.Optional}, _
       constraints:=New With {.id = "^\d+$"} _
    )

    config.Routes.MapHttpRoute( _
       name:="DefaultApiWithAction", _
       routeTemplate:="api/{controller}/{action}" _
   )

    config.Routes.MapHttpRoute( _
       name:="DefaultApiGet", _
       routeTemplate:="api/{controller}/{id}", _
       defaults:=New With {.id = RouteParameter.Optional}, _
       constraints:=New With {.httpMethod = New HttpMethodConstraint({"GET"})} _
   )

    config.Routes.MapHttpRoute( _
       name:="DefaultApiPost", _
       routeTemplate:="api/{controller}", _
       defaults:=New With {.action = "DefaultPostAction"}, _
       constraints:=New With {.httpMethod = New HttpMethodConstraint({"POST"})} _
   )

    config.Routes.MapHttpRoute( _
       name:="DefaultApiPut", _
       routeTemplate:="api/{controller}/{id}", _
       defaults:=Nothing, _
       constraints:=New With {.httpMethod = New HttpMethodConstraint({"PUT"})} _
   )