0

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!

1
  • Instead of defaulting them all, you can leave the parameters required and instead overload Get for different parameter combinations. That will let you dispense with the parameter checks. Commented May 12, 2020 at 16:05

1 Answer 1

0

You can try passing all the required parameters ignoring the optional ones.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.