2

I have been looking a ways to build a query in .NET Core Web API and I have discovered the Querybuilder in Microsoft.AspNetCore.Http.Extensions

Its not clear to me how to use it.

[Fact]
public void ThisTestFailsWithQueryBuilder()
{
    string baseUri  = "http://localhost:13493/api/employees";
    string expected = "http://localhost:13493/api/employees/1?Role=Salesman";

    var kvps = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("id", "1"),  
        new KeyValuePair<string, string>("role", "Salesman"),  
    };
    var query      = new QueryBuilder(kvps).ToQueryString();
    var finalQuery = baseUri + query;
    Assert.Equal(expected,finalQuery);
}

[Fact]
public void ThisIsSUCCESSNotUsingQueryBuilder()
{
    string baseUri  = "http://localhost:13493/api/employees";
    string expected = "http://localhost:13493/api/employees/1?Role=Salesman";

    string id          = "1";
    string role        = "Salesman";
    string partialQueryString = $"/{id}?Role={role}";
    string query       = baseUri + partialQueryString;

    Assert.Equal(expected,query);
}

How can I modify my failing test so that the one using QueryBuilder works?

1 Answer 1

3

The query represents everything after the ? in the URI. The /1 is part of the URI and not the query string.

Including what you did in the first example, finalQuery will result to

http://localhost:13493/api/employees?id=1&role=Salesman

Which is why the test assertion fails.

You would need to update the failing test

public void ThisTest_Should_Pass_With_QueryBuilder() {
    string baseUri = "http://localhost:13493/api/employees";
    string expected = "http://localhost:13493/api/employees/1?role=Salesman";

    string id = "1";
    var kvps = new List<KeyValuePair<string, string>> { 
        new KeyValuePair<string, string>("role", "Salesman"),  
    };
    var pathTemplate = $"/{id}";
    var query = new QueryBuilder(kvps).ToQueryString();
    var finalQuery = baseUri + pathTemplate + query;
    Assert.Equal(expected, finalQuery);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the clear explanation. I now understand.I could not find any samples or explanation.

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.