我的api辅助代码如下所示:
[HttpPost]
[Route("api/Login")]
public HttpResponseMessage ValidateLogin(UserModel user)
{
IEnumerable<string> customJsonInputString;
if (!Request.Headers.TryGetValues("Content-Type", out customJsonInputString))
return new HttpResponseMessage(HttpStatusCode.BadRequest);
var customJsonInputArray = customJsonInputString.ToArray();
var ProductsRequest =
Newtonsoft.Json.JsonConvert.DeserializeObject<UserModel>(customJsonInputArray[0]);
var result = _service.Fetch(
new UserModel
{
Username = user.Username,
Password = user.Password.GenerateHash()
}
);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
我试图从相同解决方案中的单独项目中调用它:
[HttpPost]
public async Task<ActionResult> Login(UserLoginModel user)
{
UserModel data = new UserModel
{
Username = user.Username,
Password = user.Password
};
using (var client = new HttpClient())
{
var myContent = JsonConvert.SerializeObject(data);
var buffer = Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var endpoint = "http://localhost:55042/api/Login";
var response = await client.PostAsync(endpoint, byteContent);
throw new NotImplementedException();
}
}
我认为问题出在
Request.Headers.TryGetValues("Content-Type", out customJsonInputString)
-s的第一个参数名称中,我已经在网上搜索过,但是没有给出正确的描述/解释,该参数名称应该是什么(嗯,我知道它是标题名称,但我也尝试使用“ ContentType”找到它,结果是相同的:“ 400错误的请求”),所以我的问题是:我究竟做错了什么?
我假设标题的名称是“ ContentType”还是“ Content-Type”是错误的吗?
最佳答案
尝试像这样更新代码:
using (var client = new HttpClient())
{
var myContent = JsonConvert.SerializeObject(data);
var endpoint = "http://localhost:55042/api/Login";
var response = await client.PostAsync(endpoint, new StringContent(myContent, Encoding.UTF8,"application/json"));
}