HttpClient 结果来自 WebAPI Request.CreateResponse (StatusCode, M
本文关键字:StatusCode CreateResponse Request 结果 WebAPI HttpClient | 更新日期: 2023-09-27 18:35:55
我有一个看起来像这样的WebAPI方法:
public HttpResponseMessage Login([FromBody] LoginType form)
{
if (LoginFails(form.Email, form.Password)
return Request.CreateErrorResponse(HttpStatusCode.OK,
"Sorry your login failed");
return this.Request.CreateResponse(HttpStatusCode.OK);
}
我有一个看起来像这样的客户端:
var sample = new LoginType()
{
login = "test",
Password = "password"
};
var client = new HttpClient();
client.BaseAddress = new Uri("www.example.com);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var result = client.PostAsJsonAsync("api/security/login", sample).Result;
问题 1:在结果变量中的哪个位置,我可以阅读消息"抱歉您的登录失败"?
问题2:当返回 CreateErrorResponse 时,返回 HttpStatusCode.OK 是否有意义?
Q1:从Response.Content
.如果内容类型为应用程序/json,则可以执行以下操作:
response.Content.ReadAsStringAsync().Result;
Q2:如果登录失败,我会返回HttpStatusCode.Unauthorized
。