What Is HTTP Status Code?
A server’s answer to a browser’s request is an HTTP status code. A website’s server receives a request from your browser when you visit it, and the server replies with a three-digit code called the HTTP status code. Status codes for HTTP responses show if a particular HTTP request has been successfully answered.
In this article, we will learn how to get the HTTP status code of a particular URL by calling just a single method in the .NET Core.
GetStatusCode Method:
public int GetStatusCode(string url) { try { using HttpClient client = new HttpClient(); HttpResponseMessage response = client.GetAsync(url).Result; return Convert.ToInt32(response.StatusCode); } catch (Exception ex) { return 404; } }
Code Explanation:
In the above method, we pass the URL as a string. Here, the URL must be in the correct format.
Example: https://www.thecodehubs.com
After executing this method, you will get the response in the below line of code.
HttpResponseMessage response = client.GetAsync(url).Result;
In the response.StatusCode, you will get the OK status.
If you want to HTTP status code in the integer format like 200 then convert it into an integer.
Convert.ToInt32(response.StatusCode);
If you want to HTTP status code in the string format like “OK” then convert it into the string.
(response.StatusCode).ToString();
In the GetStatusCode() method, you can see that we will return the 404 HTTP Status code from the exception part. It means NOTFOUND. So, whenever we request a URL that does not exist then it will go to the Exception part.
Example: https://www.sdfuygshfbsxjbcvausydgiasf.com