【问题标题】:WebAPI RC GetAll with URI parameters带有 URI 参数的 WebAPI RC GetAll
【发布时间】: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


【解决方案1】:

这是一个已在 RTM 中修复的错误。您可以通过指定默认值来获得可选参数。

public IEnumerable<string> Get(int? take = null, int? skip = null)

顺便说一句,您可以在web api odata package 中使用$skip 和$top 来实现相同的功能。

【讨论】:

  • OData 包很棒,但需要我直接公开我的实体。这是一个问题,因为我们的实体并不总是序列化,通常不建议直接公开实体。对于某些解决方案,它很棒。
猜你喜欢
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
相关资源
最近更新 更多