根据HttpWebRequest的执行位置获取不同的响应

时间:2011-09-14 20:16:29

标签: c# .net asp.net-mvc-3 httpwebrequest

我在控制台应用程序,MVC控制器和类库中执行代码时遇到了一些奇怪的问题。在前两种情况下,我得到了我期望的响应(在这种情况下是一个zip文件)但是当我尝试执行类库中的代码(我的MVC控制器中的依赖)时,我的响应中得到了一个302 HTTP状态重定向到错误页面。

所以奇怪的是它可以在我的控制台测试应用程序和MVC控制器中运行,但不能作为我的MVC项目中的依赖项。在控制器中执行此代码与作为依赖项的类库中执行此代码是否有任何区别?

我检查了Fiddler中的请求和响应,但除了ASP.NET SessionId,viewstate和响应内容之外,一切都是相同的。

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();

1 个答案:

答案 0 :(得分:0)

将主机标头更改为您尝试访问的域,而不是使用引用程序。