开发者

Getting different repsonses depending where HttpWebRequests are executed

I'm experiencing some weird issues with executing code in console application, in a MVC controller and in a class library. In the first two cases I get the response I expect (in this case a zip file) but when I try to execute the code in the class library (dependency in my MVC con开发者_StackOverflowtroller) I get a 302 HTTP Status in my response with a weird redirect to an error page.

So the strange part is that it works in my console test application and in the MVC controller, but not as a dependency in my MVC project. Is there any difference executing this code in the controller versus in a class library as a dependency?

I checked the requests and responses in Fiddler but everything is identical except of course ASP.NET SessionId, viewstate and the response content.

var cookies = new CookieContainer();

var firstRequest = (HttpWebRequest)WebRequest.Create("UrlToAspx");
firstRequest.Method = "GET";
firstRequest.KeepAlive = false;
firstRequest.CookieContainer = cookies;
var firstResponse = firstRequest.GetResponse() as HttpWebResponse;
var responseReader = new StreamReader(firstResponse.GetResponseStream());
var responseData = responseReader.ReadToEnd();
responseReader.Close();

var viewstate = ExtractViewstate(responseData);
var eventvalidation = ExtractEventValidation(responseData);

var postData = string.Format("__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&__EVENTVALIDATION={1}&ctl00%24main%24ResultFormatGroup={2}&ctl00%24main%24DropDownList1={3}&&ctl00%24main%24fromDate={4}&&ctl00%24main%24tomDate={5}&&ctl00%24main%24ImageButton1.x={6}&&ctl00%24main%24ImageButton1.y={7}", viewstate, eventvalidation, "optExport", "Transaktioner", "2011-01-01", "2011-08-17", "7", "15");

var data = Encoding.UTF8.GetBytes(postData);

var request = (HttpWebRequest)HttpWebRequest.Create("UrlToAspx");
request.Method = "POST";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.Headers.Add("Accept-Language", "sv-SE");
request.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
request.Referer = "Referer";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "referer";
request.Headers.Add("Pragma", "no-cache");
request.CookieContainer = cookies;
request.KeepAlive = false;
request.ContentLength = data.Length;

var newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();

var secondStream = new StreamReader(request.GetResponse().GetResponseStream());
var realResponseData = secondStream.ReadToEnd();


Change the host header to the domain you are trying to access instead of using a referer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜