ASP.NET WebAPI 2:如何在URI中传递空字符串作为参数

10

在我的ProductsController中有一个这样的函数:

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

当我使用这个URL发送GET请求:

 api/products?id=

它将id视为null。我该如何使其将其视为空字符串?


1
获取产品(string id = string.Empty) - Jehof
1
使用可选参数 string id = "",然后您可以调用 GET api/products/ - Ric
1
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.convertemptystringtonull(v=vs.110).aspx - ssilas777
@Ric 如果我想让 GET api/products 返回一个错误怎么办?因为我认为这样会很模糊。 - Tu Anh
歧义是什么意思?这取决于您如何设置路由等,以及是否使用RESTful API。 - Ric
显示剩余2条评论
2个回答

10

这个

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);
}

对我来说,在方法签名中的参数添加默认值就可以了。 - GRGodoi

4

我有一种情况需要区分未传递参数的情况(在这种情况下默认为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中的行为是不同的。前者允许您传递一个空字符串。 - Joel Christophel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接