.NET HttpClient将查询字符串和JSON正文添加到POST

Kev*_*n R 9 c# dotnet-httpclient

如何设置.NET HttpClient.SendAsync()请求以包含查询字符串参数和JSON正文(在POST的情况下)?

// Query string parameters
var queryString = new Dictionary<string, string>()
{
    { "foo", "bar" }
};

// Create json for body
var content = new JObject(json);

// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");

var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
    content.ToString(),
    Encoding.UTF8,
    "application/json"
);

// How do I add the queryString?

// Send the request
client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)

我见过的每个例子都说要设置

request.Content = new FormUrlEncodedContent(queryString)
Run Code Online (Sandbox Code Playgroud)

但后来我丢失了我的JSON主体初始化 request.Content

Kev*_*n R 13

我最终发现Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()这就是我所需要的.这允许我添加查询字符串参数,而无需手动构建字符串(并担心转义字符等).

注意:我正在使用ASP.NET Core,但也可以使用相同的方法 Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()

新代码:

// Query string parameters
var queryString = new Dictionary<string, string>()
{
    { "foo", "bar" }
};

// Create json for body
var content = new JObject(json);

// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");

// This is the missing piece
var requestUri = QueryHelpers.AddQueryString("something", queryString);

var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
    content.ToString(),
    Encoding.UTF8,
    "application/json"
);

// Send the request
client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)

  • @joedotnot 在此上下文中的“某物”将作为 URI 的一部分添加到“BaseAddress”中。所以它会使最终的 URI `https://api.baseaddress.com/something?foo=bar` (4认同)