【发布时间】:2013-10-25 00:46:17
【问题描述】:
以前在 WebAPI(测试版)中,我能够创建一个“GetAll”方法,该方法接受在 URI 上添加的可选参数:
http://localhost/api/product?take=5&skip=10
这似乎仍然有效,但前提是我包含所有参数。在(测试版)中,我可以省略参数(http://localhost/api/product/)并且会调用“GetAll”方法(take & skip 将为空)。我也可以省略一些参数http://localhost/api/product?take=5(跳过将为空)
public IEnumerable<ProductHeaderDto> GetAll(int? take, int? skip)
{
var results = from p in productRepository
select new ProductHeaderDto
{
Id = p.Id,
Version = p.Version,
Code = p.Code,
Description = p.DescriptionInternal,
DisplayName = p.Code + " " + p.DescriptionInternal
};
if (skip != null) results = results.Skip(skip.Value);
if (take != null) results = results.Take(take.Value);
return results;
}
在 (RC) 中,我现在得到“在控制器‘产品’上找不到与请求匹配的操作。”当缺少两个或一个参数时。我尝试在方法参数上添加 [FromUri] 但这没有影响:
public IEnumerable<ProductHeaderDto> GetAll([FromUri] int? take, [FromUri] int? skip)
我也尝试过设置默认值:
public IEnumerable<ProductHeaderDto> GetAll(int? take = null, int? skip = null)
在尝试匹配方法签名时,是否可以使用某种“可选”参数属性?
【问题讨论】:
-
控制器中有没有其他对应GET的action方法
-
我决定使用优秀的 AttributeRouting 库 - github.com/mccalltd/AttributeRouting/wiki。通过显式定义 URI,我可以让所有事情都以很大的粒度进行。使用它时,“可空”参数的问题消失了,控制器的行为与预期一样。
标签: asp.net-web-api