[英]Attribute routing - Enum not parsed
我正在尝试创建一条路线,但在这种情况下不起作用:
如果我打电话给:
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中的值。 我忘记了什么吗?
嗯,我仍然看不到您的第一个URL实际如何工作,但是第二个URL的问题是您试图将无效的数据位作为参数传递。
为了简单起见,我仅假装一分钟,您的路由定义是这样的:
routeTemplate: "api/{controller}/{type}/{id}",
defaults: new { id = RouteParameter.Optional }
如果您要在此URL http://mysite.com/product/Generic
上调用GET,那么您将遇到遇到的相同错误。 此网址将解析ProductController的控制器,其参数名为type的值将为Generic 。
但是,您的type
参数具有一个实际的GType
Type,它是一个枚举。 通用不是有效值,因此会发生错误。 这与发送“ abcd”作为int
参数的值相同。
如果您尝试调用http://mysite.com/product/Big
的get,它将可以工作,因为它可以解析该值(Big)和GType
枚举的成员。
问题是我有两个等值路由,但参数名称不同。
api/{version}/{controller}/{type}/{id}
和
api/{version}/{controller}/{id}
第二个必须是声明的最后一条路线。
您显示给我们的路线与您尝试访问的URL远程匹配。 我觉得您在寻找错误的路线。 另外, "/Product/"
不应该是“ /{controller}/"
吗?
哦,您在代码段中拼写了routeTamplate
[sic]。 我认为那是一个转录错误-我很确定编译器会对此进行吠叫。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.