Skip to main content
 首页 » 编程设计

c#之检查 WebAPI 在 C# Code Behind 中是否可用的简单、最佳方法

2024年01月18日27youxin

检查 WebAPI 是否可用的最佳方法是什么?我想在一个简单的 if() 语句中检查它,是否有可能保持相对简单?如果有更好的方法来检查。就像一个尝试/捕获。就告诉我嘛。谢谢

我想在我的代码隐藏 Page_Load 方法中包含 if 语句。因此,当 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; 
 
    } 
 
}