在做这项工作时,我想一次性回答所有问题,作为对所有人和我自己的说明:
根据 Serez 的回答 HttpContent 派生类列表如下
https://stackoverflow.com/a/42380027/914284
HttpClient PostAsync 有一些背景,具体取决于您处理的上下文!
- 在服务器上下文等待它的情况下,您可以按要发送到服务器的类型发布数据,如下所示
[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
[HttpPost]
public async Task<IActionResult> Submit([FromForm] MyModel model)
[HttpPost]
public async Task<IActionResult> Submit([FromBody] MyModel model)
在编写 FromForm 或 Body 时,它作为 FromForm 工作。FromBody 需要 json 内容,否则它需要 KeyValuePairs 作为行。它们都有一些实现,如下所示:
对于FromForm:我使用了扩展名
public static class HelperExtensions
{
public static FormUrlEncodedContent ToFormData(this object obj)
{
var formData = obj.ToKeyValue();
return new FormUrlEncodedContent(formData);
}
public static IDictionary<string, string> ToKeyValue(this object metaToken)
{
if (metaToken == null)
{
return null;
}
// Added by me: avoid cyclic references
var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
if (metaToken is not JToken token)
{
// Modified by me: use serializer defined above
return ToKeyValue(JObject.FromObject(metaToken, serializer));
}
if (token.HasValues)
{
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
{
var childContent = child.ToKeyValue();
if (childContent != null)
{
contentData = contentData.Concat(childContent)
.ToDictionary(k => k.Key, v => v.Value);
}
}
return contentData;
}
var jValue = token as JValue;
if (jValue?.Value == null)
{
return null;
}
var value = jValue?.Type == JTokenType.Date ?
jValue?.ToString("o", CultureInfo.InvariantCulture) :
jValue?.ToString(CultureInfo.InvariantCulture);
return new Dictionary<string, string> { { token.Path, value } };
}
}
对于FromBody:使用任何 json 转换器库 Newtonsoft 或 microsoft
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
两者都需要根据需求定义内容类型,例如 json (Write to header)
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
或其他用法
using (var content = new StringContent(JsonConvert.SerializeObject(answer), System.Text.Encoding.UTF8, "application/json"))
{
var answerResponse = await client.PostAsync(url, content);
//use await it has moved in some context on .core 6.0
}
如果您应该在上下文中使用授权,您也可以提供如下授权:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");