c# - 属性路由 - 枚举未解析

标签 c# enums asp.net-web-api asp.net-web-api-routing

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

如果我打电话:

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,
}

和 Controller :

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

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

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

最佳答案

嗯,我仍然看不到你的第一个网址实际上是如何工作的,但第二个网址的问题是你试图传递无效的数据位作为参数。

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

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

如果您要在此网址 http://mysite.com/product/Generic 上调用 GET,那么您将遇到与遇到的相同错误。此 URL 将解析 ProductController 的 Controller ,其参数名为 type,其值为 Generic

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

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

关于c# - 属性路由 - 枚举未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18728209/

相关文章:

ajax - 调用 Web API 字符串参数

jquery - XDomainRequest json POST 正文未在 ASP.NET Web API 调用上反序列化

c# - IFormFile 拒绝 ASP.Net Core 访问路径

c# - 为什么 "someString += AnotherString = someString;"在 C# 中有效

c# - 解析 MDX 字符串的 CLR 函数

c# - 使用 LINQ 优化图像检索

c# - 如何修复执行多个 SQL 语句的超慢 EF/LINQ 查询

c++枚举类未正确显示

enums - hybrisFlexiblesearch - 带枚举的 where 子句

enums - Nim : standard way to convert integer/string to enum