[英]HttpClient.SendAsync() returns status code 200 even if the remote server is down
A simple login method that works just fine until I shut down my API.一个简单的登录方法,在我关闭我的 API 之前都可以正常工作。 Then the try-catch block acts as intended, and an exception is thrown and caught but,
_response
comes out with a status code of "200, OK".然后 try-catch 块按预期运行,抛出并捕获异常,但是
_response
出现状态代码“200,OK”。 For the love of me, I can't figure out why.为了我的爱,我不知道为什么。 Please help!
请帮忙!
The code looks so bad mainly because of all the patching and testing I am doing on it to figure out what is happening.代码看起来很糟糕,主要是因为我正在对它进行所有修补和测试以弄清楚发生了什么。
HttpResponseMessage response = null;
public async Task<HttpResponseMessage> login(AuthModel model)
{
HttpResponseMessage response = null;
model.responseMessage = "";
var client = new HttpClient();
string text = "{\"email\": \""+model.email+"\",\"password\": \""+model.password+"\"}";
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_baseURL+"/api/user/login"),
Content = new StringContent(text, Encoding.UTF8, "application/json")
};
try
{
using (response = await client.SendAsync(request))
{
HttpResponseMessage _response = null;
//response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
//_response = response;
var body = await response.Content.ReadAsStringAsync();
var token = response.Headers.GetValues("auth-token").FirstOrDefault();
model.authToken = token;
model.name = body;
model.responseMessage = "Congratulations!";
return _response;
}
else
{
model.name = "";
model.responseMessage = await response.Content.ReadAsStringAsync();
return _response;
}
}
}
catch(Exception e) {
// model.responseMessage = e.Message;
return _response;
}
}
using "HttpResponseMessage _response = new HttpResponseMessage();"使用“HttpResponseMessage _response = new HttpResponseMessage();” was setting the _response.StatusCode to be as "200" and the code was not dealing with that.
正在将 _response.StatusCode 设置为“200”并且代码没有处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.