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

问题描述 投票:1回答:1

我一直在寻找一种在.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工作?

c# asp.net-core asp.net-core-webapi
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.