2

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.

I tried this:

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);
   }

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

  • I would suggest to expose a Get method from web-api and ping it from your C# code. – Sagar Sep 06 '16 at 07:50
  • Can you provide some code? an example would help me very much –  Sep 06 '16 at 07:51
  • 1
    is your API unavailable a lot? If so, then maybe look at fixing it. If not, then instead of testing its availability every time you load the page (which will cost you the time and resources for an additional HTTP request), just make your application handle connection (and other) errors from the API gracefully instead. I'm not sure that continuously testing its existence is good design really. Just design for occasional failure. If there's a big availability problem, then look at how you can sort that out instead of working round it. – ADyson Sep 06 '16 at 07:55
  • the problem is that my application contains sensitive data. if the webapi crashes which luckily doesnt happen a lot, the user can access my page. Allthough it can happen..... so i have to check to add a bit more security to my site. Do you know how i would be able to check? @ADyson –  Sep 06 '16 at 07:57
  • so is the API handling security for you? In that case, in whatever method you call to check the security, you just check if you get an appropriate response from the API. If that call fails, then you block the site. If you're calling the API from C#, you'll likely get an exception if the call fails, so you can detect that and act accordingly. Please correct me if I've misunderstood you. – ADyson Sep 06 '16 at 08:02
  • exactly, thats what i wanna do.... do you have some code example? or any source where i can get some code for this operation? –  Sep 06 '16 at 08:04
  • i just dont wanna do it via a method. i wanna check in a if-statement.... @ADyson –  Sep 06 '16 at 08:06
  • @AlessandroMinneci you can create a read only web api as described [here](http://www.asp.net/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api#Exercise1) – Sagar Sep 06 '16 at 08:11
  • thank, but this doesnt help. i just need to check in a if statement. the webapi is already set up and finished. @sagar –  Sep 06 '16 at 08:12
  • @AlessandroMinneci I think you're getting hung up on the if statement. In order to check the web api, you have to make a call to it. If everything's fine you'll get a HTTP 200 response (OK), if it's completely dead you'll get a 404 (Not Found), or if there's another problem you might get a different code (500 is common for general problems). The standard C# ways to call the API will throw an exception if they don't get a 200 status. So catch that exception and do whatever you need to. – ADyson Sep 06 '16 at 08:13
  • i understand. so i could call a method in my page load that communicates with my web api. if my exception catches the site will be blocked right? any idea how that method will look? @ADyson –  Sep 06 '16 at 08:16
  • Possible duplicate of [what's a good/proper way to check whether a Web API is available?](http://stackoverflow.com/questions/17555167/whats-a-good-proper-way-to-check-whether-a-web-api-is-available) – Paul Zahra Sep 06 '16 at 08:19
  • nah, in this question, he wants to use a try/catch. im trying a if statement or any other example that works @PaulZahra –  Sep 06 '16 at 08:20
  • What's your objection to try/catch? It seems like the simplest way. – ADyson Sep 06 '16 at 08:27
  • as i said im willing to see how i could do it with a try/catch. can you show me a example of how you would do it.(snippet of the method). and could you answer it in a "real" answer so other people dont have to read everything. they can just look at your question @ADyson –  Sep 06 '16 at 08:29
  • 1
    @AlessandroMinneci He doesn't 'want to use' a try/catch... he merely suggests it and in the same sentence asks if there's a better way to do it... and you ended up using a try/catch anyway lol. – Paul Zahra Sep 06 '16 at 10:45

2 Answers2

5

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;

    }

}
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • System.Net - as I've shown in the code. It's in the WebClient class. – ADyson Sep 06 '16 at 08:36
  • just realised it's not static, will edit the answer very slightly. – ADyson Sep 06 '16 at 08:37
  • yes i know that its in System.net. however i have to add a object assembly. which one? –  Sep 06 '16 at 08:39
  • you can add an explicit reference to system.net into your project if you want, but I'm not sure it's necessary. I'm pretty sure I've used it without. Might be different in a forms project, I normally use MVC. – ADyson Sep 06 '16 at 08:41
5

Assuming this is your flow:

  • User loads your page, you check whether the API is up.
  • User enters data, submits your form.
  • Using the submitted data, you call the actual API call you're interested in.

It makes no sense to want to check an API before issuing the actual request. Sure, the simple "GET" might succeed, and then the actual request might fail, having proven nothing. The API can go down between the two requests, or the "check" request does something different than the actual request, causing the latter to fail anyway.

Also, given most network I/O are very leaky abstractions, you need exception handling code around them anyway. So whether you use HttpWebRequest, WebClient or HttpClient, you will need to wrap the code in a try-catch block anyway.

See How to see if HttpClient connects to offline website, .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned, How to check if Web server is up? (C#) and so on.

However, it seems like the API handles authorization and authentication for you, and that the API sometimes "fails", causing your code to detect this as a valid attempt to use your site, so it seems you just need to fix the code that actually performs the API call. No if() statement is going to help you there.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272