从以编程方式创建的webrequest获取查询字符串变量

时间:2013-02-26 10:41:30

标签: c# asp.net httpwebrequest

我正在以编程方式创建这样的网络请求

        string url = "http://aksphases:201/min-konto/printpdf.aspx?id=149656222&name=Ink%20And%20Toner";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.CookieContainer = new CookieContainer(); // required for HttpWebResponse.Cookies
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        byte[] data = Encoding.UTF8.GetBytes("email=mymail&password=1234");
        request.ContentLength = data.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        HttpWebResponse myWebResponse = (HttpWebResponse)request.GetResponse();
        Stream ReceiveStream = myWebResponse.GetResponseStream();

printpdf.aspx页面中(您可以在url中看到它)我想以编程方式执行此URL时获取查询字符串参数。当我尝试通常的方式时

HttpContext.Current.Request.QueryString["id"]

它不起作用。 有什么我在做错的方式。或者有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

你在网络应用程序中的确切位置是什么?

HttpContext.Current.Request.QueryString["id"]

以下是我认为您应该尝试的内容: 在您的客户端应用中:

    string url = "http://aksphases:201/min-konto/printpdf.aspx?id=149656222&name=Ink%20And%20Toner";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    // try this
    Debug.WriteLine("About to send request with query=\"{0}\"", request.RequestUri.Query);
    // and check to see what gets printed in the debug output windows

    request.CookieContainer = new CookieContainer(); // required for HttpWebResponse.Cookies
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    byte[] data = Encoding.UTF8.GetBytes("email=mymail&password=1234");
    request.ContentLength = data.Length;

而在你的ASPX页面中,试试这个:

    protected void Page_Load(object sender, EventArgs e) {
        var theUrl = this.Request.Url.ToString();
        Debug.WriteLine(theUrl); // is this the exact URL that you initially requested ?
        // if you have FormsAuthentication or other redirects
        // this might get modified if you're not careful

        var theId = this.Request.QueryString["id"];
        Debug.WriteLine(theId);
    }