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

纵饮孤独 提交于 2021-01-29 04:28:25

问题


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:


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


来源:https://stackoverflow.com/questions/50197800/how-to-build-a-query-with-microsoft-aspnetcore-http-extensions-querybuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!