Is there any to make sure that DNS errors has been occurred after getting WebException in the following code?
WebRequest request = WebRequest.Create(uri);
....
WebResponse response = request.EndGetResponse(asyncResult);
String comparison might be one way. By checking the error message we can be sure. But depending on culture the message string can vary. So this may not be the best way for checking DNS error.
One of the the WebExceptionStatus values is NameResolutionFailure. This indicates DNS errors.
Instead of relying (ever!) on the response message received, I would rely on the StatusCode of the WebResponse received. An HTTP status code in the range 4xx (400-499) would be indicative of DNS issues or errors in locating the resource.
Related
I found this code from here it works for uri like "https://google.com" but it doesn't work for something like "https://172.61.58.168/Account/Login/". I actually don't know why. I have an App using that URI that has an API that I need to call. I can successfully do an api-call and I just decided to make a validation first if the base uri exist and is valid.
Help. Thanks.
code:
bool isHttpValid = false;
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create("https://172.16.85.186/Account/Login/") as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
response.Close();
isHttpValid = true;
}
catch
{
//Any exception will returns false.
isHttpValid = false;
}
First of all you should use HttpClient instead of WebRequest, then you are checking that a HTTP request is valid, however your using a HTTPS URL.
If you want a method that check both HTTP and HTTPS URLs, you have to think how are you going to manage HTTPS certificates, due to that exception:
System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Maybe you want to add that custom certificate as secure, or you want to remove the security policy that checks the SSL certificates (I don't recommend it), following that other question.
I hope this can help you.
I'm trying to understand something about exception handling with a HttpWebRequest.
I have a client library and it's making a request to a WebAPI controller;
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
r.Method = "POST";
r.ContentType = "application/json";
foreach (var header in request.Headers)
{
r.Headers.Add(header.Key, header.Value.ToString());
}
r.ContentLength = request.RequestBody.Length;
using (StreamWriter writer = new StreamWriter(r.GetRequestStream()))
writer.Write(request.RequestBody);
I know the request will throw an exception, and contain the message entity already exists - 1234.
When I get the response;
using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
return reader.ReadToEnd();
return "Invalid";
}
I get a WebException thrown. So, the caller of the request has a try..catch in it. And I get the WebException. What I get is a protocol error, not the 500 internal server error that was thrown (using correct status codes to represent the message comes later). Now if I read the Response of the WebException, it does contain my message and the stacktrace.
Questions
Why do I not get a status code of 500 in my response, why does it throw a protocol error?
Is there a more correct way of handling the request?
I have searched around and found some people getting this issue when not using the correct headers etc. But as far as I can tell, I have added all the headers that I can and still get the same behavior.
An 500 internal server error usually means that the API received the request but threw an unhandled exception while processing it, thus the "Internal Server Error".
You may log to a database or file all your API's unhandled exceptions to help your debugging process. Good luck.
I have the following code in my method:
// make the FTP request
var request = (FtpWebRequest)WebRequest.Create(serverUri);
request.KeepAlive = true;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
return (FtpWebResponse)request.GetResponse();
The serverUri is valid and this works if the directory does not exist already on the server. However, if the directory does already exist a System.Net.WebException : The remote server returned an error: (550) File unavailable (e.g., file not found, no access) occurs.
Why does this exception occur when I call request.GetResponse() instead of setting the FtpWebResponse object's StatusCode to FtpStatusCode.ActionNotTakenFileUnavailable which is 550?
I find information on how to handle the exception and get the status code and description from it. But I would like to know why the exception is thrown in the first place instead of setting the response object's status code and letting the coder decide if it warrants an exception.
Because getting an error code after making an Http request matches perfectly with the Exception semantics of the language. You don't actually have a meaningful response to get back and since it is an "exceptional" case it makes sense to translate the web error to a WebException.
This is actually behaving as designed. You'll need to catch that specific exception and then interrogate the response. Per the MSDN documentation:
If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
So, the code might look like this:
try
{
return (FtpWebResponse)request.GetResponse();
}
catch (WebException we)
{
// interrogate the WebException for the response data you're looking for
}
I need to check whether a given host is replying to HTTP web requests.
So, all I need to do is HttpWebRequest.Create(someURI) and check the response, right?
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
TimeSpan timeOut = TimeSpan.FromSeconds(timeOutInSeconds);
webRequest.Timeout = (int)timeOut.TotalMilliseconds;
webRequest.Proxy = proxy;
webRequest.AllowAutoRedirect = false; // get extra information with this turned off, but doesn't affect the problem
response = webRequest.GetResponse() as HttpWebResponse;
Well, the problem that's come up is that if someURI is blocked by our firewall (e.g. "gibber.com" is blocked), then I get back a valid HttpWebResponse, it doesn't throw, and the ResponseURI property is set to the blocked URI ("gibber.com") even though it's actually our server responding.
Within the HTTP header there will be a Location key and its value is the IP of the local server. But I don't want to parse text to work out if a request actually bounced. What's the correct way to do this?
Thanks
check to see if response.ResponseUri corresponds to the given host or your firewall.
It seems to be occurring only one machine and none of the other machines.
HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("https://connect.zystemsgo.com/auto/");
myRequest.Method = "GET";
SetCertificatePolicy();
Application.DoEvents();
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(),System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
I tried searching other 400 request errors, but it is not clear. How do I go about debugging this?
HTTP Error 400 means Bad Request. This is being returned by the server.
Usually, when I'm debugging HTTP requests, I use Fiddler to monitor the requests and responses and find out what's going on. It never fails.
(Not really an answer, but too big for comment)
For what it's worth, I ran the following Python code (too lazy to spin up C# :), and it worked fine:
import httplib
conn = httplib.HTTPSConnection('connect.zystemsgo.com')
conn.request('GET', '/auto/')
resp = conn.getresponse()
data = resp.read()
print data # expected ouput, just like visiting in a browser
print resp.status # 200
Are you sure you are showing us the URL that is actually failing, or is your code a more general example?
Perhaps the server certificate is not installed on that machine? I wouldn't expect a HTTP 400 in that case, but it's the only thing I can think of so far...
it is a bad request error .Are there no parameters in the request?
Can you post the response message,it will give some idea of what is going wrong.
The code that i supplied in the comment above works.
WebClient webClient = new WebClient();
webClient.DownloadFile("Your complete url for the file", #"c:\myfile.txt");
you need to have permission to write in the directory of your choice.
You could also try and use the async download if you want.I am not getting why it would not work on a certain machine.