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

C# ASP.NET WebAPI 2:如何将空字符串作为URI中的参数传递,c#,asp.net,asp.net-web-api,null,query-string,C#,Asp.net,Asp.net Web Api,Null,Query String,我的产品控制器中有这样一个函数: public IHttpActionResult GetProduct(string id) { var product = products.FirstOrDefault((p) => p.Id == id); return Ok(product); } 当我使用此URL发送GET请求时: api/products?id= 它将id视为null。如何将其视为空字符串 public IHttpActionResult GetProdu

我的
产品控制器中有这样一个函数:

public IHttpActionResult GetProduct(string id)
{
    var product = products.FirstOrDefault((p) => p.Id == id);
    return Ok(product);
}
当我使用此URL发送GET请求时:

 api/products?id=
它将
id
视为null。如何将其视为空字符串

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

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


GetProduct(string id=string.Empty)使用可选参数
string id=”“
,然后您可以调用
GET-api/products/
@Ric如果我想让GET-api/products返回错误怎么办?因为我认为它在什么意义上是模糊的?这取决于你如何设置你的路由等,如果你是resful的api,对我来说,它只是工作时添加一个默认值的参数在方法签名。这正是我需要的。在.NET Framework和.NET Core中,行为似乎有所不同。前者允许您传入一个空字符串。
[HttpGet()]
public string GetMethod(string code = null) {
   if (Request.Query.ContainsKey(nameof(code)) && code == null)
      code = string.Empty;

   // ....
}