我有以下代码连接到带有基本身份验证的api:
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) => {
var request = HttpWebRequest.Create(url);
request.Credentials = new NetworkCredential(email, password);
args.Result = request.GetResponse();
};
worker.RunWorkerCompleted += (sender, e) => {
String msg = "";
// need to check whether there has been an error
// otherwise trying to get the result throws an exception
if (e.Error == null) {
var code = ((HttpWebResponse)e.Result).StatusCode;
if (code == HttpStatusCode.OK)
msg = "Connectivity OK";
else if (code == HttpStatusCode.Unauthorized)
msg = "Wrong username";
else if (code == HttpStatusCode.Forbidden)
msg = "Wrong password";
else if (code == HttpStatusCode.NotFound)
msg = "Wrong organisation";
else
msg = "Connectivity Error: " + code;
} else {
msg = "Connectivity error: " + e.Error.Message;
}
label.Text = msg;
log.d(msg);
};
我想获取状态代码,以便能够告诉用户用户名,密码或组织是否错误。不幸的是,如果出现网络错误,尝试获取e.Result会导致另一个错误,所以我只能在没有错误的情况下检查状态代码。
我尝试过使用各种其他假定的异步C#网络方法,例如: webclient.downloadStringAsync但它们不是真正的异步; DNS解析是在当前线程上完成的。我也不能使用async和await,因为我必须使用Net Framework 4.0。
答案 0 :(得分:0)
在这里找到了我自己问题的答案:https://stackoverflow.com/a/4700154/519074
4xx和5xx范围内的服务器响应会抛出WebException,因此您必须检查它。此代码有效:
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) => {
var request = HttpWebRequest.Create(url);
request.Credentials = new NetworkCredential(email, password);
// TODO: set proxy settings if necessary
try {
args.Result = ((HttpWebResponse)request.GetResponse()).StatusCode;
} catch (WebException we) {
args.Result = ((HttpWebResponse)we.Response).StatusCode;
}
};
worker.RunWorkerCompleted += (sender, e) => {
String msg = "";
var code = (HttpStatusCode)e.Result;
if (code == HttpStatusCode.OK)
msg = "Connectivity OK";
else if (code == HttpStatusCode.Forbidden)
msg = "Wrong username or password";
else if (code == HttpStatusCode.NotFound)
msg = "Wrong organisation";
else
msg = "Connectivity Error: " + code;
label.Text = msg;
log.d(msg);
};