同一个HttpVerb的多个动作

Alf*_*ono 9 c# asp.net-web-api asp.net-web-api-routing

我有一个Web API控制器,其中包含以下操作:

    [HttpPut]
    public string Put(int id, JObject data)

    [HttpPut, ActionName("Lock")]
    public bool Lock(int id)

    [HttpPut, ActionName("Unlock")]
    public bool Unlock(int id)
Run Code Online (Sandbox Code Playgroud)

并映射了以下路线:

        routes.MapHttpRoute(
            name: "Api",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        routes.MapHttpRoute(
            name: "ApiAction",
            routeTemplate: "api/{controller}/{action}/{id}"
        );
Run Code Online (Sandbox Code Playgroud)

当我提出以下请求时,一切都按预期工作:

PUT /api/items/Lock/5
PUT /api/items/Unlock/5
Run Code Online (Sandbox Code Playgroud)

但是当我试图提出要求时:

PUT /api/items/5
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

Multiple actions were found that match the request:
    Put(int id, JObject data)
    Lock(int id)
    Unlock(int id)
Run Code Online (Sandbox Code Playgroud)

我尝试在默认路由中添加一个空操作名称,但这没有帮助:

[HttpPut, ActionName("")]
public string Put(int id, JObject data)
Run Code Online (Sandbox Code Playgroud)

有关如何将默认RESTful路由与自定义操作名称相结合的任何想法?

编辑:路由机制不会被控制器的选择混淆.它被单个控制器上的动作选择所迷惑.我需要的是在没有指定动作时匹配默认动作.希望澄清事情.

tug*_*erk 6

这是来自默认操作选择器的预期错误ApiControllerActionSelector.你基本上有三个对应HTTP Put动词的动作方法.也请记住,默认的动作选择认为这些都是原始的.NET类型简单的动作参数类型,知名的简单类型(System.String,System.DateTime,System.Decimal,System.Guid,System.DateTimeOffset,System.TimeSpan)和基本简单类型(例如:Nullable<System.Int32>).

作为您的问题的解决方案,我将为这些创建两个控制器,如下所示:

public class FooController : ApiController { 

    public string Put(int id, JObject data)
}

public class FooRPCController : ApiController { 

    [HttpPut]
    public bool Lock(int id)

    [HttpPut]
    public bool Unlock(int id)
}
Run Code Online (Sandbox Code Playgroud)

路线如下所示:

routes.MapHttpRoute(
    name: "ApiAction",
    routeTemplate: "api/Foo/{action}/{id}",
    defaults: new { controller = "FooRPC" }
);

routes.MapHttpRoute(
    name: "Api",
    routeTemplate: "api/Foo/{id}",
    defaults: new { id = RouteParameter.Optional, controller = "Foo" }
);
Run Code Online (Sandbox Code Playgroud)

另一方面(与您的主题不完全相关),我有三篇关于动作选择的博客文章,特别是复杂的类型参数.我鼓励你检查它们,因为它们可能会给你一些更多的观点:


Alf*_*ono 2

在Giscard Biamby的帮助下,我找到了这个答案,它为我指明了正确的方向。最终,为了解决这个具体问题,我这样做了:

routes.MapHttpRoute(
    name: "ApiPut", 
    routeTemplate: "api/{controller}/{id}",
    defaults: new { action = "Put" }, 
    constraints: new { httpMethod = new HttpMethodConstraint("Put") }
);
Run Code Online (Sandbox Code Playgroud)

谢谢@GiscardBiamby