ASP.NET WebAPI 2: How to pass empty string as parameter in URI
13,388
Solution 1
This
public IHttpActionResult GetProduct(string id = "")
{
var product = products.FirstOrDefault((p) => p.Id == id);
return Ok(product);
}
or this:
public IHttpActionResult GetProduct(string id)
{
var product = products.FirstOrDefault((p) => p.Id == id ?? "");
return Ok(product);
}
Solution 2
I have a situation where I need to distinguish between no parameter passed (in which case default of null is assigned), and empty string is explicitly passed. I have used the following solution (.Net Core 2.2):
[HttpGet()]
public string GetMethod(string code = null) {
if (Request.Query.ContainsKey(nameof(code)) && code == null)
code = string.Empty;
// ....
}
Author by
Tu Anh
Updated on July 18, 2022Comments
-
Tu Anh almost 2 years
I have a function like this in my
ProductsController
:public IHttpActionResult GetProduct(string id) { var product = products.FirstOrDefault((p) => p.Id == id); return Ok(product); }
When I send a GET request with this URL:
api/products?id=
it treats
id
as null. How can I make it to treat it as an empty string?-
Jehof over 8 yearsGetProduct(string id = string.Empty)
-
Ric over 8 yearsUse optional parameter
string id = ""
then you can callGET api/products/
-
ssilas777 over 8 years
-
Tu Anh over 8 years@Ric What if i want GET api/products to return an error? Because I think it will be ambiguous
-
Ric over 8 yearsambiguous in what sense? it depends how you have setup your routing etc and if you are uring resful api,
-
Tu Anh over 8 years@Ric I afraid that people may think GET api/products will return all products.
-
Ric over 8 yearsI would also think the same!
-
-
rohitwtbs about 8 yearsFor me it just worked when adding a default value to the parameter in the method signature.
-
Joel Christophel almost 4 yearsExactly what I needed. Looks like the behavior is different in .NET Framework and .NET Core. The former allows you to pass in an empty string.