本文介绍了如何使用Microsoft.AspNetCore.Http.Extensions.QueryBuilder建立查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在寻找一种在.NET Core Web API中构建查询的方法,并且在Microsoft.AspNetCore.Http.Extensions
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
我不清楚如何使用它.
[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
的测试成功?
How can I modify my failing test so that the one using QueryBuilder
works?
推荐答案
查询代表URI中?
之后的所有内容./1
是URI的一部分,而不是查询字符串.
The query represents everything after the ?
in the URI. The /1
is part of the URI and not the query string.
包括您在第一个示例中所做的一样, finalQuery
将得出
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.
您需要更新失败的测试
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);
}
这篇关于如何使用Microsoft.AspNetCore.Http.Extensions.QueryBuilder建立查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!