I'm learning, how to code rest api in C# and I have some problems with query string parameters parsing.
API works this way: 1: I have 1 endpoint api/project which can have some parameters in query string eg: api/project?type=informational or api/project?project_id=1&user_id=2
This endpoint function takes parameters and based on which of them are called by users, it calls other functions, which filters information based on the query strings.
So endpoint function looks lie:
[HttpGet]
[Route("api/project")]
public HttpResponseMessage projects(string type = "1", string project_id = "1", string user_id = "1" ....)
{
try
{
if (type != "1")
{
return getProjectsByType(type);
}
else if (project_id != "1" && user_id != "1")
{
return getProjectsByIds(project_id, user_id);
}
else
{
return Request.CreateResponse(System.Net.HttpStatusCode.OK);
}
}
catch (Exception e)
{
return Request.CreateErrorResponse(System.Net.
HttpStatusCode.BadRequest, "Something went wrong");
}}
So function looks at the if statements and check values. If it finds values, which are not default and match with the condition, it calls a method which filters information.
The problem is kinda obvious, parse logic for query strings works but it is really not nice code, especially if a user may add 50 different parameters, It would require 50 conditions.
Can you give me tip, how to make this a bit nicer?
Thanks for all tips!
Getfor different parameter combinations. That will let you dispense with the parameter checks.