C# WebAPI:将URI参数反序列化为poco操作参数
给定这样的路线定义:C# WebAPI:将URI参数反序列化为poco操作参数,c#,.net,url-routing,asp.net-mvc-4,asp.net-web-api,C#,.net,Url Routing,Asp.net Mvc 4,Asp.net Web Api,给定这样的路线定义: routes.MapHttpRoute( name: "Categories", routeTemplate: "{controller}/Categories/{entity}/{property}", defaults: new { action = "Categories", entity = RouteParameter.Optional, property = "Name" }
routes.MapHttpRoute(
name: "Categories",
routeTemplate: "{controller}/Categories/{entity}/{property}",
defaults: new { action = "Categories", entity = RouteParameter.Optional, property = "Name" }
);
控制器的动作声明如下:
public IEnumerable<Category> Categories(string property);
public IEnumerable<Category> Categories(string entity, string property);
public IEnumerable<Category> Categories(Type entity, string property);
但是我需要用一个自定义的反序列化程序反序列化字符串。我准备好了自定义反序列化程序,也就是MediaTypeFormatters,用于从内容体提交的内容。这里我的问题是,在这种情况下,源是一个URI参数,而不是内容体
这就引出了我的问题:
public enum EntityType
{
Address,
Department
}
public class UserController : ApiController
{
public IEnumerable<Category> Categories(EntityType entity, string property)
{
}
}
公共枚举EntityType
{
地址:,
部门
}
公共类用户控制器:ApiController
{
公共IEnumerable类别(EntityType实体、字符串属性)
{
}
}
您仍然需要代码来处理实体类型,但这似乎比让客户端向您发送随机的CLR类型名称更安全?然后模型绑定将验证URI中的{entity}段。因此,如果客户机请求User/Categories/FavoriteBeer,他们将得到400个错误请求public enum EntityType
{
Address,
Department
}
public class UserController : ApiController
{
public IEnumerable<Category> Categories(EntityType entity, string property)
{
}
}
公共枚举EntityType
{
地址:,
部门
}
公共类用户控制器:ApiController
{
公共IEnumerable类别(EntityType实体、字符串属性)
{
}
}
您仍然需要代码来处理实体类型,但这似乎比让客户端向您发送随机的CLR类型名称更安全?然后模型绑定将验证URI中的{entity}段。因此,如果客户机请求User/Categories/FavoriteBeer,他们将得到400个错误请求1.我的印象是,路线不是按顺序映射的,而是按参数名称映射的,如果我只提供2个参数中的1个,那么可选的参数当然是不匹配的参数。2.然后,我必须在每次添加另一种实体时更新枚举,而不是让它自动为新的实体工作。然后我宁愿接受太多的字符串,当我不能映射类型时,给400。3.是的,我也这么想。所以我不能用那个结构。但是我可以使用什么构造呢。我的印象是,路线不是按顺序映射的,而是按参数名称映射的,如果我只提供2个参数中的1个,那么可选的参数当然是不匹配的参数。2.然后,我必须在每次添加另一种实体时更新枚举,而不是让它自动为新的实体工作。然后我宁愿接受太多的字符串,当我不能映射类型时,给400。3.是的,我也这么想。所以我不能用那个结构。但是我可以使用什么构造呢?