2013-04-09 62 views
2

是否有可能采取行动?是否可以在Web API .net中使用params进行操作?

[HttpGet] 
    public List<Product> GET(int CategoryId, string option, params string[] properties) 
    { 
     List<Product> result = new List<Product>(); 
     result = BusinessRules.getProductsByCategoryId(CategoryId); 
     return result; 
    } 

从而使URL看起来像“/ API /产品/类别编号/全/名称/产品ID /”

它调用可能的动作,因为属性是可选的,但在性能参数总是空。我甚至尝试过在请求的主体中传递Name和ProductID参数,而仍然属性为null。我想使用“params”,因为我想将0..N的论述传递给动作。

这里是路线模板。

config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{CategoryId}/{option}/{*properties}", 
      constraints: new { CategoryId = @"\d+" }, 
      defaults: new { option = RouteParameter.Optional, properties = RouteParameter.Optional } 
    ); 

回答

2

退房这个帖子:http://www.tugberkugurlu.com/archive/asp-net-web-api-catch-all-route-parameter-binding

它经过创建自定义的参数绑定到任何包罗万象的查询参数转换为数组。我想不是全局注册,但用它来装饰,你会需要它,像这样的想法:

public HttpResponseMessage Get([BindCatchAllRoute('/')]string[] tags) { ... 

当然,你可以随时使用常规的查询字符串。这当然是很容易:

[HttpGet] 
public List<Product> GET(int CategoryId, string option, [FromUri] string[] properties = null) 
{ 
    List<Product> result = new List<Product>(); 
    result = BusinessRules.getProductsByCategoryId(CategoryId); 
    return result; 
} 

,并调用它像这样: /API /产品/ 123 /全/属性=名称&性能=产品ID

相关问题