假如如有以下Api
/// <summary>
/// 获取注册码信息
/// </summary>
/// <param name="licenseStr"></param>
/// <returns></returns>
[HttpPost]
[Route("detail-by-license")]
public async Task<IHttpActionResult> GetLicenseAsync([FromBody] string licenseStr)
在使用以下方式请求时 licenseStr 始终为空
var uri = $"{LicenseDomain}/api/license/detail-by-license";
var client = new HttpClient();
var postContent = new StringContent("", Encoding.UTF8, "application/json");
client.PostAsync(uri, postContent).GetAwaiter().GetResult();
需要改用以下方式即可, (此处的 key 为空即可)
var postContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", license) });
2021年1月4日补充: 以上方式在net core webapi中并不适用, 原因请参考这篇文章(https://www.cnblogs.com/CreateMyself/p/6246977.html)
可以使用以下的方式,可以将字符串先进行一次序列化
var postContent = new StringContent(JsonSerializer.Serialize(license), Encoding.UTF8, MediaTypeNames.Application.Json);