最佳的方法来检查WebAPI是否在C

最佳的方法来检查WebAPI是否在C

本文介绍了简单,最佳的方法来检查WebAPI是否在C#中可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查WebAPI是否可用的最佳方法是什么?我想在一个简单的if()语句中对其进行检查,是否有可能使它相对简单?是否有更好的检查方法.像尝试/捕获一样.就告诉我嘛.谢谢

What is the best way to check if the WebAPI is available or not? I want to check it in a simple if() statement, is it even possible to keep it relatively simple? if there is a better way to check. like a try/catch. just tell me. Thanks

我想在我的代码后方Page_Load方法中包含if语句.因此,当API不可用时,我可以阻止该网站.

I want to include the if-statement in my code-behind Page_Load Method. So I can block the site when the API is not available.

我尝试过:

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是自动构建的.如果发生异常,我将引用我的错误站点.

I am trying to Download a string from my webapi. my uri is built automatically. if a exception happens, i refer to my Error site.

还有其他想法吗?这种方法有效,但不是很干净

Any other ideas? this method works, but its not very clean

推荐答案

应该执行类似的操作(假设您的API具有支持相当简单的GET请求的方法).如果没有收到HTTP 200(OK)响应,则可能是有问题,您应该采取措施使您的网站无法使用(例如,隐藏所有内容).

Something like this should do it (assuming your API has a method which supports a fairly simple GET request). If you don't get a HTTP 200 (OK) response, there's likely a problem, and you should take steps to make your site un-usable (e.g. hide all the content).

如果有这样的话,最好将其放在您的母版页中:

It might be best to put this in your master page, if you have one:

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;

    }

}

这篇关于简单,最佳的方法来检查WebAPI是否在C#中可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:58