2

I am working on an ASP.Net Core web API using REST verbs with optional query string parameters.

For example, the API call looks like this;

http://localhost:5010/servicetypecode?stc=123

or http://localhost:5010/servicetypecode?mailclasscode=fc

I am using code like this to set up the query strings

    public IActionResult Get([FromQuery] string mailclasscode, [FromQuery] string stc) { ... }

So, in my method body, I am evaluating each string individually like this...

    if (!string.IsNullOrEmpty(mailclasscode)) { ... }


    if (!string.IsNullOrEmpty(stc)) { ... }

However, I would like to allow my users to just make a straight up GET to the API with no query string parameters provided and return a list of all records, unfiltered.

So a call like this;

http://localhost:5010/servicetypecode

But I would prefer not to have to do this in my method body, especially if I were to have a lot of query string parameters;

if (string.IsNullOrEmpty(mailclasscode) && string.IsNullOrEmpty(stc)) { ... }

Is there a way to simply determine if no query string parameters were provided without evaluating every possible query string parameter?

Also, is there a better way to evaluate query string parameters than testing every possible parameter, in the case where I were to pass a lot of different query string parameters?

Thanks in advance for any help you can provide.

1 Answer 1

2

You can check the incoming request.

if (this.HttpContext.Request.QueryString.HasValue)

Also as a note, if you have a lot of query string parameters, you can use a single class instead of multiple parameters in the method signature.

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

2 Comments

ATerry, thanks. This worked perfectly. The other part of the question I was asking was more about a better way of processing multiple query string parameters than just using multiple if statements within the body of the method (whether I am using multiple query strings or a class in the method signature). I am trying to use a single GET method but provide multiple filtering options so, currently, I am testing for each possible query string parameter using multiple if statements. This works but looks a bit cluttered.
If you looking to do more of a query based api, almost like a data access api, you can make use of IQueryable with a limited or full implementation of OData. Also, you can look at GraphQL. These are both frameworks that will take your returned IQueryable and apply the necessary filters.

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.