问题
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