I have the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;
try
{
request.GetResponse();
}
catch
{
}
How can I catch a specific 404 error? The WebExceptionStatus.ProtocolError can only detect that an error occurred, but not give the exact code of the error.
For example:
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.ProtocolError)
{
throw ex;
}
}
Is just not useful enough... the protocol exception could be 401, 503, 403, anything really.
Best web development and SEO practices dictate that any webpage which does not exist, return an HTTP response code of 404, or Not Found. Basically, this response code means that the URL that you're requesting does not exist.
A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.
What Is A 404 Error And Why Can't The Pages Open? A 404 error message is a Hypertext Transfer Protocol (HTTP) status code indicating the server could not find the requested website. In other words, your web browser can connect with the server, but the specific page you're trying to access can't be reached.
try
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
// Process the stream
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null)
{
var resp = (HttpWebResponse) ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
// Do something
}
else
{
// Do something else
}
}
else
{
// Do something else
}
}
Use the HttpStatusCode Enumeration
, specifically HttpStatusCode.NotFound
Something like:
HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
//
}
Wherewe
is a WebException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With