无法在 WebApi OData 中实现多个 GET 方法

Cannot implement multiple GET methods in WebApi OData


我在 MVC4 Web API 项目 .NET4 中使用 OData V3。
WebAPI注册方式为:

public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling =
                  Newtonsoft.Json.PreserveReferencesHandling.None;

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<ClientModel>("ODClient");
            builder.ComplexType<ClientStatus>();
            builder.ComplexType<ClientType>();

            var edmmodel = builder.GetEdmModel();

            config.Routes.MapODataRoute(
                    routeName: "odata",
                    routePrefix: "odata",
                    model: edmmodel
            );
        }

OData 控制器是:

        [HttpGet]
        [Queryable(AllowedQueryOptions = AllowedQueryOptions.All, PageSize = 25)]
        public IQueryable<ClientModel> Get() 
        {
            var model = ...
            return model;
        }

        [HttpGet]
        public ClientModel Get([FromODataUri] int id)
        {
            return new ClientModel();
        }

    [HttpDelete]
    public void Delete([FromODataUri] int id)
    {
    }

此查询运行良好:
http://localhost:59661/odata/ODClient?$filter=id eq 3

但是这个查询不起作用:
http://localhost:59661/odata/ODClient(3)
它对所有项目执行第一个 GET 查询。

删除也不行(请求类型为DELETE):
http://localhost:59661/odata/ODClient(3)

收到的错误是:
"No HTTP resource was found that matches the request URI 'http://localhost:59661/odata/ODClient(12)'."

根据问题评论,问题在于默认路由约定为参数分配名称的方式。键实际上被赋予默认名称 "key",因此切换到该名称有效。

可以通过创建自定义路由约定来自定义名称,该约定使用 "id" 值填充路由数据 table,或者使用基于属性的路由,在这种情况下,参数名称可以匹配路径模板中指定的名称。