Reputation: 11
There are many posts on WebResponse 403 error but my situation is a little different. I have created a console application that will run as a task on my server. The console application passes user emails in WebRequest and waits for WebResponse to receive the uri with the returning parameters. The code below worked perfectly a few days ago but one of the other programmers added a new parameter for a return web address. I know for a fact that this is causing the 403 error because if I paste the uri in IE with new parameter it works. But since I have a console application a return web address is something I cannot do, at least I don't think so.
Unfortunately the programmer said that he cannot change it back and said that there is a way to receive the uri or the entire page content and I can process it that way. I still have no clue what he was talking about because StreamReader requires a WebResponse and pretty much all other solutions I could think of.
Even though I get a 403 error the response still has the uri with the parameters I need because I can see it in IE in the web address. So all I need is the response uri. I would appreciate any help you have to offer. Below is the method giving me problems.
String employeeInfo = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest
.Create("http://example.com/subsub.aspx?instprod=xxx&vabid=emailaddress");
using (HttpWebResponse webResponse =
(HttpWebResponse)request.GetResponse()) //Error occurs here. 403 Forbidden
{
Uri myUri = new Uri(webResponse.ResponseUri.ToString());
String queryParamerter = myUri.Query;
employeeInfo = HttpUtility.ParseQueryString(queryParamerter).Get("vres");
if (employeeInfo != "N/A")
{
return employeeInfo;
}
else
{
employeeInfo = "0";
return employeeInfo;
}
}
}
catch (WebException)
{
employeeInfo = "0";
return employeeInfo;
}
Upvotes: 0
Views: 1082
Reputation: 32701
Let's follow Jim Mischel's idea. We'll handle the WebException and use the Response property of the exception.
String employeeInfo = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/subsub.aspx?instprod=xxx&vabid=emailaddress");
using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse()) //Error occurs here. 403 Forbidden
{
Uri myUri = new Uri(webResponse.ResponseUri.ToString());
String queryParamerter = myUri.Query;
employeeInfo = HttpUtility.ParseQueryString(queryParamerter).Get("vres");
if (employeeInfo != "N/A")
{
return employeeInfo;
}
else
{
employeeInfo = "0";
return employeeInfo;
}
}
}
catch (WebException ex)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if(response.StatusCode != HttpStatusCode.Forbidden)
{
throw;
}
Uri myUri = new Uri(response.ResponseUri.ToString());
String queryParamerter = myUri.Query;
employeeInfo = HttpUtility.ParseQueryString(queryParamerter).Get("vres");
if (employeeInfo != "N/A")
{
return employeeInfo;
}
else
{
employeeInfo = "0";
return employeeInfo;
}
}
Upvotes: 2