Alessandro Minneci Alessandro Minneci - 2 months ago 32
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

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

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.

Answer

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;

    }

}
Comments