12

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?

7
  • 1
    GetProduct(string id = string.Empty) Commented Jan 6, 2016 at 10:04
  • 1
    Use optional parameter string id = "" then you can call GET api/products/ Commented Jan 6, 2016 at 10:05
  • 1
    msdn.microsoft.com/en-us/library/… Commented Jan 6, 2016 at 10:07
  • @Ric What if i want GET api/products to return an error? Because I think it will be ambiguous Commented Jan 6, 2016 at 10:24
  • ambiguous in what sense? it depends how you have setup your routing etc and if you are uring resful api, Commented Jan 6, 2016 at 10:26

2 Answers 2

11

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

For me it just worked when adding a default value to the parameter in the method signature.
5

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; // .... } 

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.