ASP.NET WebAPI 2:如何在URI中传递空字符串作为参数
本文关键字:字符串 参数 URI WebAPI NET ASP | 更新日期: 2023-09-27 18:29:20
我的ProductsController
:中有这样的函数
public IHttpActionResult GetProduct(string id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
return Ok(product);
}
当我用以下URL发送GET请求时:
api/products?id=
则将CCD_ 2视为空。如何将其视为空字符串?
此
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):
[HttpGet()]
public string GetMethod(string code = null) {
if (Request.Query.ContainsKey(nameof(code)) && code == null)
code = string.Empty;
// ....
}