Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I got this code which is trying to capture 410 code, but it's throwing error at first line and not going through rest of the code,

 HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone)
            {

Is there any way I can capture the 410 code other then above one.

Answer code with help of answer below

  try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
               if (((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.NotFound || ((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.Gone)
                {
share|improve this question

1 Answer

up vote 1 down vote accepted

This is how GetResponse method works. It throws an exception when it does not get code 200.

Try to put your request.GetResponse() into try .. catch block. Catch WebException. In catch clause you can handle situation, when the status code is not 200.

share|improve this answer
so in catch block i use, if (ex.StatusCode == HttpStatusCode.Gone , sorry not sure, an example code will do the job, thanks :) – yaron 19 mins ago
if i put in catch block i get this, Use of unassigned local variable 'response' – yaron 18 mins ago
You should not use response as you did not get it correctly on that point. Use WebException.Response istead, so if you named your exception variable as ex you should use ex.Response – ŁukaszW.pl 17 mins ago
Error 2 Operator '==' cannot be applied to operands of type 'System.Net.WebResponse' and 'System.Net.HttpStatusCode' – yaron 14 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.