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

时间:2016-10-27 17:37:04

标签: 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);

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

request.Content = new FormUrlEncodedContent(queryString)

然后我在request.Content

中丢失了我的JSON主体初始化

3 个答案:

答案 0 :(得分:9)

我最终找到了我需要的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);

答案 1 :(得分:1)

我建议你为此目的使用RestSharp。它基本上是HttpWebRequest的包装器,可以完全按照您的要求执行操作:可以轻松编写url和body参数并将结果反序列化。

网站示例:

var client = new RestClient("http://example.com");

var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile(path);

// execute the request
IRestResponse response = client.Execute(request);

答案 2 :(得分:-2)

这很简单,对我有用:

responseMsg = await httpClient.PostAsJsonAsync(locationSearchUri, new { NameLike = "Johnson" });

请求的正文看起来像{ NameLike:"Johnson" }