Alessandro Minneci Alessandro Minneci - 1 year ago 200
ASP.NET (C#) Question

Easy, best way to check if WebAPI is available in C# Code Behind

What is the best way to check if the WebAPI is available or not? I want to check it in a simple

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

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

Answer Source

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)
      System.Net.WebClient client = new System.Net.WebClient();
      string result = client.DownloadString("");
    catch (System.Net.WebException ex)
      //do something here to make the site unusable, e.g:
      myContent.Visible = false;
      myErrorDiv.Visible = true;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download