2

我正在尝试制定路线,但在这种情况下不起作用:

如果我打电话:

http://mysite.com/api/v1/product/Generic/1A 

工作正常。

如果我打电话:

http://mysite.com/api/v1/product?=Generic 

也可以,但是当我打电话时:

http://mysite.com/api/v1/product/Generic 

我收到此错误:

{
 "Message":"The request is invalid.",
 "MessageDetail":"The parameters dictionary contains a null entry for parameter 'type'
 of non-nullable type 'GType' for method 'System.Net.Http.HttpResponseMessage 
 Get(GType)' in 'MySite.ControllersApi.V2.ProductController'. An optional parameter must 
 be a reference type, a nullable type, or be declared as an optional parameter."
}

我的路线代码:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute
        (
            name: "DefaultApi",
            routeTemplate: "api/{version}/{controller}/{type}/{id}",
            defaults: new { id = RouteParameter.Optional, version = "v1", controller = "Product" }
        )
    }
}

public enum GType
{
    Big,
    Small,
    Generic,
}

和控制器:

public HttpResponseMessage Get(GType type)
{
    ...
}

public HttpResponseMessage Get(GType type, string id)
{
    ...
}

因此,Web API 不会解析 URL 中的值。我忘了什么吗?

4

3 回答 3

2

问题是我有两条相等的路线,但参数名称不同。

api/{version}/{controller}/{type}/{id} 

api/{version}/{controller}/{id}

第二个必须是最后声明的路由。

于 2013-09-11T14:27:43.150 回答
2

好吧,我仍然看不到你的第一个 url 是如何工作的,但是第二个 url 的问题是你试图传递一个无效的数据位作为参数。

为简单起见,我将假装您的路线定义是这样的:

 routeTemplate: "api/{controller}/{type}/{id}",
 defaults: new { id = RouteParameter.Optional }

如果您要在此 url 上调用 GET http://mysite.com/product/Generic,那么您将遇到同样的错误。此 url 将解析ProductController的控制器,其参数名为type,其值为Generic

但是,您的type参数的实际类型为GType,它是一个枚举。Generic 不是有效值,因此会发生错误。这与发送“abcd”作为参数的值是一样的int

如果您尝试调用 get to http://mysite.com/product/Big,它会起作用,因为它能够解析该值 (Big) 和GType枚举成员。

于 2013-09-11T04:08:36.160 回答
0

您向我们展示的路线与您尝试访问的 URL 远程不匹配。我有一种感觉,你正在寻找错误的路线。另外,不应该"/Product/"是“ /{controller}/"

哦,你routeTamplate在片段中拼错了[原文如此]。我认为这是一个转录错误——我很确定编译器会对此大喊大叫。

于 2013-09-10T21:38:45.777 回答