Multiple NULL values in Web API Get Method Parameter

Viewed 1881

I have this kind of sample code below that calls an API using get method:

CrudService.getAll("sampleurl/param1/param2/param3");

From that sample, param1 and param2 can be null/blank value. What happens is that the value of param3 goes to param1 when it comes to the API Controller.

How can I maintain the right values for the parameter even if there can be several null/blank values? TIA.

5 Answers
CrudService.getAll("sampleurl/param1/param2/param3");

You have to pass a dummy value for param1 so if param1 is empty keep it "param1". various possible call based on empty params :

  • ("sampleurl/param1/param2/2");

  • ("sampleurl/param1/3/2");

  • ("sampleurl/param1/param2/param3");

So when the call goes to API, check there is param1=param1 ignore the value you have to keep 3 values in order to match the signature of API in any case.

if your using asp API the parameters should send like this.

  string url = $"https://example.com/api/controllerName/Action?parms1={value}&parms2={value}";
                                    response = client.GetAsync(url).Result;

And if you are using asmx you should edit the web service to handle the parameters like this:

CrudService.getAll("sampleurl",parm1,parm2,etc..);

I hope this will help you.

If you choose such a url structure, it means you have some sort of hierarchy structure. For example mysite.com/vehicle/car/mercedes/classc/details/engine could show or return details of the engine of a class C mercedes. It goes without saying that not transmitting the brand or the car model doesn't make sense.

If you want to keep this hierarchical structure, you must expose an url that permits you to mention the category "undefined" in the structure like: mysite.com/vehicle/car/brandlesscars/mybrandlessmodel/details/engine

If the segments of your url represent a parameter of a query but not a path sequence to access to a more detailed section, it is way better to have a url with parameters like this: mysite.com/vehicle/details/engine?type=car&brand=mercedes&model=classc.

you could explicitly send the request with parameters names and values just like the answer from Paul and applying this to your example: CrudService.getAll("http://sampleurl/controller/action?param1="value"&param2="value&param3=value");

i hope this will help you

The answer of @Jin Thakur is one way to do it but I did this instead. Similar to the answer of @Sinan. Thanks all.

From JS:

CrudService.getAll("/api/home/monitor/param?param1=&param2=&param3=val1");

From C# API:

[Route("api/home/monitor/param")]
[HttpGet]
public IHttpActionResult GetSomeValue(string param1, string param2, string param3)
{

//Some Codes

}
Related