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;

   // ....
}
    
Share:
13,388
Tu Anh
Author by

Tu Anh

Updated on July 18, 2022

Comments

  • Tu Anh
    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
      Jehof over 8 years
      GetProduct(string id = string.Empty)
    • Ric
      Ric over 8 years
      Use optional parameter string id = "" then you can call GET api/products/
    • ssilas777
      ssilas777 over 8 years
    • Tu Anh
      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
      Ric over 8 years
      ambiguous in what sense? it depends how you have setup your routing etc and if you are uring resful api,
    • Tu Anh
      Tu Anh over 8 years
      @Ric I afraid that people may think GET api/products will return all products.
    • Ric
      Ric over 8 years
      I would also think the same!
  • rohitwtbs
    rohitwtbs about 8 years
    For me it just worked when adding a default value to the parameter in the method signature.
  • Joel Christophel
    Joel Christophel almost 4 years
    Exactly 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.