I am having some strange problems with code execution in a console application, in the MVC controller and in the class library. In the first two cases, I get the answer that I expect (in this case a zip file), but when I try to execute the code in the class library (dependency in my MVC controller), I get the status of HTTP 302 in my response with a strange redirect to the page with an error.
So the weird part is that it works in my test application for the console and in the MVC, but not as a dependency in my MVC project. Is there any difference in the execution of this code in the controller compared to the class library as a dependency?
I checked the requests and responses in Fiddler, but everything is identical, except, of course, the ASP.NET SessionId, viewstate, and 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();
source share