如何使用Microsoft.AspNetCore.Http.Extensions.QueryBuilder构建查询

时间:2018-05-06 08:38:23

标签: c# asp.net-core asp.net-core-webapi

我一直在寻找在.NET Core Web API中构建查询的方法,我在Microsoft.AspNetCore.Http.Extensions中发现了Querybuilder

我不清楚如何使用它。

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

如何修改失败的测试,以便使用QueryBuilder的测试工作?

1 个答案:

答案 0 :(得分:1)

查询表示URI中?之后的所有内容。 /1是URI的一部分,而不是查询字符串。

包括您在第一个示例中所做的操作,finalQuery将导致

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

这就是测试断言失败的原因。

您需要更新失败的测试

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