developer9969
developer9969

Reputation: 5236

How to build a query with Microsoft.AspNetCore.Http.Extensions.QueryBuilder

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?

Upvotes: 2

Views: 5728

Answers (1)

Nkosi
Nkosi

Reputation: 247363

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);
}

Upvotes: 3

Related Questions