【发布时间】:2020-10-26 13:34:05
【问题描述】:
网络 API: 我也尝试在字符串 stringcontent 之前使用 [FormBody] 和 [FromForm]。
// POST api/<MAUserController>
[HttpPost("AuthenticateUser")]
public async Task<ActionResult<MAUser>> PostAsync(string stringcontent)
{
//stringcontent is null
}
客户代码:
List<KeyValuePair<string, string>> postParameters = new List<KeyValuePair<string, string>>();
postParameters.Add(new KeyValuePair<string, string>("Email", Email));
postParameters.Add(new KeyValuePair<string, string>("Password", Password));
var jsonString = JsonConvert.SerializeObject(postParameters);
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
//httpClient.DefaultRequestHeaders.Add("Email", Email);
//httpClient.DefaultRequestHeaders.Add("Password", Password);
using (var response = await httpClient.PostAsync(API_URL, stringContent))
{
if (response.IsSuccessStatusCode)
{
//Success code
}
else
{
//Handle unsuccessful here
}
}
【问题讨论】:
-
远射:也许你需要
API_URL + "/AuthenticateUser"作为 URL? -
没有 API_URL 已经有正确的 URI 位置。调试时断点确实在 webapi 中命中..
-
您正在从客户端以 JSON 格式发布结构化数据。那么为什么 API 只是试图接受一个纯字符串呢?这没有多大意义。让它接受具有正确结构的模型对象。 ASP.NET 将负责将 JSON 属性绑定到模型属性。
-
你不应该有
([FromBody] YourModel content)吗?其中YourModel是具有要从您发布的json 反序列化的相关属性的类。 -
另外,
postParameters应该只是postParameters = new { Email = .., Password = .. };
标签: c# json asp.net-core asp.net-core-webapi dotnet-httpclient