REST API health check - c#

I have number of APIs which is not being hosted by me, so I have no control of the API itself. What I'm trying to achieve is to check whether the APIs is online or not.I already tried several way:
Sent a HTTP request to the API endpoint with HEAD method
Sent a blank HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.NotFound)
return false;
return true;
}
Ping the server
But somehow my end result is not accurate enough. It shows offline but when I manually try to invoke the API, it seems okay. Anybody got a solution?

What about using an API Health Check service?
Some links that can help you:
https://www.runscope.com/
https://www.getpostman.com/docs/postman/monitors/intro_monitors
https://blog.runscope.com/posts/build-a-health-check-api-for-services-underneath-your-api
https://nordicapis.com/monitor-the-status-of-apis-with-these-4-tools/
https://apigee.com/about/blog/technology/api-health-free-tool-monitoring-apis-public-beta-now

The first option should be good as long as the server can respond to a HEAD request. If it doesn't there should be some safe GET endpoint which can be used instead.
It also makes sense to time the health check so that if the API server is not alive, it won't freeze your app.

You can use Postman Monitors to achieve this. Postman offers 1000 free monitor runs on the free account and notifications via email on failures. You can set it up to run on a schedule by specifying the hour/day/week that the monitor should run at.
Simply create a postman collection: https://learning.getpostman.com/docs/postman/collections/creating_collections/
Add your HTTP Health check request in the collection.
Create a monitor on the collection: https://learning.getpostman.com/docs/postman/monitors/setting_up_monitor/
And set up the frequency that it should run with.
You can also manually trigger monitors via the Postman API: https://docs.api.getpostman.com

Related

How To Prevent HttpWebRequest with long response from timing-out Azure Web App

We are using an HttpWebRequest in C# to get data from an internet resource in our Azure Web App. The problem is that Azure has a limitation on how long it keeps the connection alive (around 240 seconds). Due to the nature of our application, the response will sometimes take longer than 240 seconds. When this happens, the webpage will go white, and the "View Source" will show zero source code (which has made this issue difficult to debug).
Here's some sample code to illustrate:
webRequest = WebRequest.Create(PAGE_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
webRequest.Timeout = Timeout.Infinite;
webRequest.KeepAlive = true;
StreamWriter requestWriter2 = new
StreamWriter(webRequest.GetRequestStream());
requestWriter2.Write(postString);
requestWriter2.Close();
WebResponse response = webRequest.GetResponse();
Stream stream = response.GetResponseStream();
Adding webRequest.Timeout and webRequest.KeepAlive did not solve the issue.
jbq on this thread mentioned he had a workaround by sending a "newline character every 5 seconds", however did not explain how to accomplish this exactly. He was answering a question about an Azure VM, but I think an Azure Web App would have similar behaviors with respect to what I believe are the load balancers that are responsible for the timeout.
The Question:
How can I send one HttpWebRequest, and then send another HttpWebRequest while the previous one is running with a blank line to maintain the connection and prevent the Azure load balancer(?) from timing out the azure application? Would a new session variable need to be used? Perhaps an asynchronous method? Do I need to send the "pinging" request before the main request? If so, how would this look in implementation? Or is it something else entirely? Please provide some source code as an example :)
Note: you do not need to use an HttpWebRequest to replicate this issue. Attach a debugger from within Visual Studio to a live Azure Web App. Place a breakpoint within Visual Studio at any piece of code. When that breakpoint is hit, after roughly 4 minutes you'll see the page in your browser stop loading and go white with an empty source. So, it's not specifically related to HttpWebRequest, but that is an operation that would typically cause this sort of issue since some responses take longer than 4 minutes.
*EDIT: I think what I am looking for is an implementation of Asynchronous methods. I will update this post as I find a satisfactory implementation.
If you are making an HttpWebRequest to an Azure Website then you use ServicePointManager.SetTcpKeepAlive on your client code which uses HttpWebRequest.
https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.settcpkeepalive(v=vs.110).aspx
The 4 minute timeout that you are talking about is an IDLE timeout over the TCP layer and setting this will ensure that your client (who is using HttpWebRequest) sends ACK packet over TCP so that the connection doesn't get idle.
If your web application is making a HttpWebRequest to some other service, you can still use this function but that will just ensure that the Idle timeout is not hit when calling the remote service. Your actual HTTP request to the Azure Webapp may still hit the 4 minute time and if the client to your Azure web app is not HttpWebRequest, then again the 4 minute idle timeout will bite you...
The best thing to do here is to change the code a bit to implement a JOB Model kind of pattern where-in you make a server call which returns a JOBID. The client then queries the server using this JOBID in a polling fashion and when the job completes on the server the status of this JOBID can be set to COMPLETED in which case the client can then retrieve the data. You can use Webjobs in Azure Webapps to achieve something like this.
Hope this helps...

C# WSDL Client Request Packages

I am currently adding a SOAP-WSDL Service to my project using "Add Service Reference". it creates all necessary classes and functions for me to call. Some of these functions dont give me a response. After 1 minute delay i get a timeout exception. However when i forge the request using Postman (a chrome extension for making network requests) it gets full response. i got suspicious and started to inspect network using Wireshark. after inspection i saw that problem was at the service. but i can't make them fix that. so i need to imitate Postman request using C#.
Main difference between mine and postman is, Postman posts all necessary data in single request for a response, but my client posts just http headers waits for a Http Continue and continues sending necessary data. i guess this breaks the service.
Here are wireshark screenshots for Postman and my client
(Postman is on the left of image and right one is my .net client - sorry for my perfect paint skills)
Is there any configuration on .net wsdl client with basicHttpBinding i can configure to make single request for a call?
edit: when i further investigated my C# client i saw that .net http layer send an initial POST with saying (Expect: 100 Continue), after it receives continue it continues to send SOAP Envelope
edit2: i changed my code to issue request using HttpWebRequest, but .net still sends header and post body with seperate requests (even when i disabled Expect: 100 Continue) and in my theory this breaks service.
question2: is there anyway to say HttpWebRequest, don't split header and body? send all of them in single request?
edit3: i solved the problem. but it wasn't about 100 Continue. service was being broken because of missing User-Agent Header
For HttpWebRequest you can add the following to your .config file - we use this on our service. I'm not, however, sure how it impacts WCF channels.
<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
</configuration>
i finally solved the problem. after long inspections and tries i saw that remote service stops responding in the middle of the data communication if i dont add User-Agent HTTP Header. so i added http header using IClientMessageInspector before every request
here is wcf code if anybody needs it
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty realProp;
object property;
//check if this property already exists
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
realProp = (HttpRequestMessageProperty) property;
if (string.IsNullOrEmpty(realProp.Headers["User-Agent"])) //don't modify if it is already set
{
realProp.Headers["User-Agent"] = "doktorinSM/2.1";
}
return null;
}
realProp = new HttpRequestMessageProperty();
realProp.Headers["User-Agent"] = "doktorinSM/2.1";
request.Properties.Add(HttpRequestMessageProperty.Name, realProp);
return null;
}

Parallel HTTPRequest using HttpClient in Windows 8 app

I am using HttpClient for sending HTTP requests and receiving HTTP responses in my Windows 8 app. I have few questions on the same:
1) Can I send multiple/parallel HTTP requests using a single HttpClient object? Is there a recommended way to use HttpClient object efficiently?
2) What is the difference when I create HttpClient object every time and when I re-use the same object for each new request?
3) I am tracking the requests and responses using Fiddler. What I found out is that the response time in Fiddler is different than the response time I am calculating manually inside my App. The response time for a request in Fiddler is always lower than the calculated response time in my app. Can anybody please tell me why it is like that?
4) One more thing I came across is that for every request it is doing HTTPS handshake. Instead it should do it only first time. I checked it using Fiddler and it is clearly visible there. Is there any property I need to set in HttpClient object to stop this from doing it every time.
5) Whether HttpClient is thread-safe?
1 & 5:
HttpClient manual:
The following methods are thread safe:
CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync
2 & 4:
HttpClient manual:
The HttpClient class instance acts as a session to send HTTP requests.
3:
Fiddler acts as a proxy. Your browser sends the request to Fiddler, which forwards it to the origin server. This adds upon the request time.
Make sure that you use the same HttpClient object for each async HttpRequest which will prevent it from overlapping the requests

How to ping a website / ip that is deployed in iis

I need to make a website that is designed to monitor / check the connectivity of our internal applications that is deployed on iis, Its like a list of links to our internal websites that we developed. The question is, how would I be able to check if a website is up and running? and how would I check if a website is down? I will simply display the links of our system and color it based on their status, green for up, and red if its down or has errors.. hoping for your advice. sample codes would be appreciated.
Just load anything from that server, if it loads your site is up and running, if it doesnt load, then just generate an error or show red
The simplest way to do this is to have a windows service or scheduled task running which performs WebRequests against the list of websites and checking the status codes.
If a status code of 200 is returned, show green. Anything else (4xx, 5xx, timeout), show red. Have the service store the results in a database and have the 'red-green' page read from that database.
That would be a generic, one-size-fits-all solution. It may not work for all sites, as some sites could have basic authentication, in which case your monitor will incorrectly record that the site is down. So you would need to store metadata against the sites and perform basic authentication (or any other business logic) to determine whether it's up or down.
If you have access to the websites you want to monitor then I would have thought the easiest way is to put a status page on the websites you want to monitor designed to be polled by your service. This way if the website is up you can get more advanced status information from it by reading the page content.
If you just want to check the http status then just access any page on the website (preferably a small one!) and check the response status code.
Something like
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(Url);
//if (AuthRequired())
// request.Credentials = new NetworkCredential(Username, Password);
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
then you can read the response.StatusCode

MonoDroid HttpWebRequest and WebClient unreliable?

I am having a lot of trouble using Webrequests in MonoDroid and getting timeouts at random. My code works fine then sometimes all requests just timeout and don't work.
I have verified the webservices used in my requests are not the problem.
Here is an example of some code that I may use to request some data from a webservice using MonoDroid:
bool bolOk = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://www.website.com/service/");
request.Timeout = 20000;
request.Credentials = gv_objCredentials;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse ()) {
bolOk = response.StatusCode == HttpStatusCode.OK;
}
As you can see it is basic stuff. I use code like the above always on another thread to the UI using ThreadPool.QueueUserWorkItem or TaskFactory.
What I have noticed is that if the requests start timing out from my app and I plug it in to my computer then debug the app from MonoDevelop the requests work without timing out. I am not sure if this means anything. This is similar to testing the webservices from my computer using a browser on the same network as the phone. The webservices always work without any issues.
What is the best way to make Webrequests from MonoDroid?
How can I ensure my requests are always successful and won't timeout if the webservice is operating correctly?
I had the Issue on Xamarin 4.2.6 and 4.2.8.
Thanks to Xamarin support, they identified the issue and suggested I targeted my build to armeabi-v7a rather than armeabi in my project properties (some multi-core processor issue described here)
Depending on whether you plan to support multi-core processors or not, you should check our this post and may need to manually edit your .csproj file.
There's a new version of Mono for Android (4.2.5) that fixes a number of bugs with the WebRequest and webRequestStream. You can check the release notes here: http://docs.xamarin.com/android/Releases/Mono_For_Android_4/Mono_for_Android_4.2.5
I suggest downloading the latest bits and check if it works. If not, please file a bug and they will surely fix it in the next version of the product.

Categories