Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebAPI 2: How to pass empty string as parameter in URI

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?

like image 968
Tu Anh Avatar asked Jan 06 '16 10:01

Tu Anh


2 Answers

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);
}
like image 87
Steve Harris Avatar answered Nov 16 '22 21:11

Steve Harris


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;

   // ....
}
    
like image 4
LMK Avatar answered Nov 16 '22 21:11

LMK