我有一些使用网络服务的代码。我不是每次都从服务中检索会话密钥,而是想用我设置的会话变量来尝试响应,如果我收到403错误,请获取新的会话密钥并重试。
在我有限的思维中,嵌套try/catch
语句很有意义,但我只是意识到必须有更好的方法。我在这里读过一些提及lambda expressions with using statements
和Helpers
之类的帖子,但这些也可能是外星人间行星科学给我的礼物。
总是愿意学习我想知道是否有人有建议(详情或细节链接)?这里的一切都有效,我只需要比嵌套try
语句更好的方法(请和谢谢)。一如既往,你们摇滚!
public string getMySessionkey
将使用登录凭据进入服务器以获取会话密钥(所有其他查询都需要)
searchPacket = stringbuilder with parameters and session key
if (Session["MySessionKey"] != null)
{
sessionKee = Session["MySessionKey"].ToString();
}
else
{
sessionKee = getMySessionkey(_cbE, _cbP);
System.Web.HttpContext.Current.Session.Add("MySessionKey", sessionKee);
}
try
{
mySearchResults = getResults(searchPacket.ToString());
vbResultz += Server.HtmlEncode(mySearchResults) ;
}
catch (WebException wx)
{
HttpWebResponse webresponse ;
webresponse = (HttpWebResponse)wx.Response;
switch (webresponse.StatusCode)
{
case HttpStatusCode.InternalServerError:
...
break;
case HttpStatusCode.Forbidden: // 403
vbResultz = "You aint got no valid session key!";
// code here to get a new session key and try again
break;
default:
throw;
}
}
答案 0 :(得分:2)
使用具有有限出现次数的循环。只要您的通话有效,请退出循环。
var maxNumberOfTries = 3;
var currentTry = 0;
var success = false;
do
{
currentTry += 1;
// Try whatever here. If it works, set success variable to true
if (success) break;
} while (currentTry <= maxNumberOfTries)
if (!success)
{
// If code reaches here, whatever had to be done has been tried <maxNumberOfTries> times and did not work
}
编辑:以下是您的代码中实现的上述示例:
var maxNumberOfTries = 3;
var currentTry = 0;
var flag = false;
do
{
currentTry += 1;
try
{
mySearchResults = getResults(searchPacket.ToString());
vbResultz += Server.HtmlEncode(mySearchResults) ;
flag = true;
}
catch (WebException wx)
{
HttpWebResponse webresponse ;
webresponse = (HttpWebResponse)wx.Response;
switch (webresponse.StatusCode)
{
case HttpStatusCode.InternalServerError:
...
flag = true;
break;
case HttpStatusCode.Forbidden: // 403
vbResultz = "You aint got no valid session key!";
// code here to get a new session key and try again
break;
default:
throw;
}
}
if (flag) break;
} while (currentTry <= maxNumberOfTries)
if (!flag)
{
// If code reaches here, whatever had to be done has been tried <maxNumberOfTries> times and did not work
}
在成功尝试获取密钥时,flag
变量将设置为true,或者如果发生内部服务器错误,则将其设置为true。如果您有403响应,它将再次尝试,最多三次。