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?
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);
}
                        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;
   // ....
}
    
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With