【问题标题】:ASP.NET WebAPI 2: How to pass empty string as parameter in URIASP.NET WebAPI 2:如何在 URI 中将空字符串作为参数传递
【发布时间】:2016-01-06 10:02:16
【问题描述】:

我的ProductsController 中有这样的功能:

public IHttpActionResult GetProduct(string id)
{
    var product = products.FirstOrDefault((p) => p.Id == id);
    return Ok(product);
}

当我使用此 URL 发送 GET 请求时:

 api/products?id=

它将id 视为空值。我怎样才能让它把它当作一个空字符串?

【问题讨论】:

  • GetProduct(string id = string.Empty)
  • 使用可选参数string id = ""则可以调用GET api/products/
  • @Ric 如果我希望 GET api/products 返回错误怎么办?因为我觉得会模棱两可
  • 在什么意义上模棱两可?这取决于您如何设置路由等,以及您是否使用 resful api,

标签: c# asp.net asp.net-web-api null query-string


【解决方案1】:

这个

public IHttpActionResult GetProduct(string id = "")
{
    var product = products.FirstOrDefault((p) => p.Id == id);
    return Ok(product);
}

或者这个:

public IHttpActionResult GetProduct(string id)
{
    var product = products.FirstOrDefault((p) => p.Id == id ?? "");
    return Ok(product);
}

【讨论】:

  • 对我来说,在方法签名中为参数添加默认值时它才起作用。
【解决方案2】:

我有一种情况,我需要区分没有传递参数(在这种情况下分配了默认值 null)和显式传递空字符串。我使用了以下解决方案(.Net Core 2.2):

[HttpGet()]
public string GetMethod(string code = null) {
   if (Request.Query.ContainsKey(nameof(code)) && code == null)
      code = string.Empty;

   // ....
}
    

【讨论】:

  • 正是我需要的。看起来 .NET Framework 和 .NET Core 中的行为不同。前者允许你传入一个空字符串。
猜你喜欢
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2015-04-17
  • 1970-01-01
相关资源
最近更新 更多