简单的 HttpRequestMessage 但不工作
Simple HttpRequestMessage but not working
我正在编写一个简单的 dotnet 核心 API,在搜索控制器下,如下所示:
[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
return await service.getorder(ordername,siteid)
}
The swagger UI where the path https://devehost/search/order
test pretty work, but when I use another client to call this api by below
client = new HttpClient {
BaseAddress = new Uri("https://devehost")
};
var request = new HttpRequestMessage(HttpMethod.Get, "Search/order") {
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new("ordername", "pizza-1"),
new("siteid", "1"),
})
};
var response = await client.SendAsync(request);
状态码总是return错误的请求。但是邮递员在工作,我能知道里面的问题吗?
谢谢
对于 GET
请求,参数应在查询字符串中发送,而不是请求正文。
GET - HTTP | MDN
Note: Sending body/payload in a GET
request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.
对于 .NET Core,您可以使用 the Microsoft.AspNetCore.WebUtilities.QueryHelpers
class 将参数附加到 URL:
Dictionary<string, string> parameters = new()
{
["ordername"] = "pizza-1",
["siteid"] = "1",
};
string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);
我正在编写一个简单的 dotnet 核心 API,在搜索控制器下,如下所示:
[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
return await service.getorder(ordername,siteid)
}
The swagger UI where the path https://devehost/search/order
test pretty work, but when I use another client to call this api by below
client = new HttpClient {
BaseAddress = new Uri("https://devehost")
};
var request = new HttpRequestMessage(HttpMethod.Get, "Search/order") {
Content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new("ordername", "pizza-1"),
new("siteid", "1"),
})
};
var response = await client.SendAsync(request);
状态码总是return错误的请求。但是邮递员在工作,我能知道里面的问题吗?
谢谢
对于 GET
请求,参数应在查询字符串中发送,而不是请求正文。
GET - HTTP | MDN
Note: Sending body/payload in aGET
request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.
对于 .NET Core,您可以使用 the Microsoft.AspNetCore.WebUtilities.QueryHelpers
class 将参数附加到 URL:
Dictionary<string, string> parameters = new()
{
["ordername"] = "pizza-1",
["siteid"] = "1",
};
string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);