检查 WebAPI 是否可用的最佳方法是什么?我想简单地检查一下if()
陈述,是否有可能保持相对简单?如果有更好的检查方法。就像尝试/捕捉一样。就告诉我嘛。谢谢
我想在我的代码隐藏中包含 if 语句Page_Load
方法。这样当 API 不可用时我可以阻止该网站。
我试过这个:
try
{
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
string response = client.DownloadString(baseuri + Constants.API_LEHRLING + lehrlingID);
}
catch (Exception ex)
{
string url = "AccessDenied.aspx";
Server.Transfer(url, true);
}
我正在尝试从我的 webapi 下载字符串。我的 uri 是自动构建的。如果发生异常,我会参考我的错误站点。
还有其他想法吗?这个方法有效,但不是很干净
像这样的事情应该可以做到(假设您的 API 有一个支持相当简单的 GET 请求的方法)。如果您没有收到 HTTP 200 (OK) 响应,则可能存在问题,您应该采取措施使您的网站无法使用(例如隐藏所有内容)。
如果您有母版页,最好将其放入母版页中:
protected void Page_Load(object sender, EventArgs e)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
string result = client.DownloadString("http://www.example.com/api/TestMethod");
}
catch (System.Net.WebException ex)
{
//do something here to make the site unusable, e.g:
myContent.Visible = false;
myErrorDiv.Visible = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)