unable to read values from Request.Params in c#

2019-08-11 02:51发布

问题:

I have following piece of code which is troubling me to read the value from Request.Params. Right now I just want to read values (in receiver) that I'm passing from sender i.e. username and SAMLResponse.

Sender

protected void Button1_Click(object sender, EventArgs e)
{
    HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("MY URL");
    httpWReq.Method = "Post";
    XElement obj = XElement.Load(@"Load.xml");
    StringBuilder postData = new StringBuilder();
    postData = postData.Append("username=user&SAMLResponse=").Append(obj.ToString());                

    byte[] data = Encoding.UTF8.GetBytes(postData.ToString());

    httpWReq.Method = "POST";
    httpWReq.ContentType = "text/xml;encoding='utf-8'";
    httpWReq.ContentLength = data.Length;

    using (Stream stream = httpWReq.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }

    HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}

Receiver

public ActionResult LoginSSO()
{
    string rawSamlData, WindowName;
    SSOModel objSSOModel = new SSOModel();
    string str = Request.Params["username"];
    str = Request.Params["SAMLResponse"];
    ...
    ..
}

Error:

Any idea, what is going wrong?

回答1:

Can you change this line:

httpWReq.ContentType = "text/xml;encoding='utf-8'";

to this:

httpWReq.ContentType = "application/x-www-form-urlencoded";

And give us a result?

https://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx



回答2:

I see a few issues with your code.

  1. Encoding - you should encode the XML file when you do obj.ToString() as it may contain characters that will confuse things.
  2. content type - You are telling the receiver that you are sending XML but you are really sending a form. So you should set the content type to application/x-www-form-urlencoded


回答3:

This works in my application.

  1. As other answerers said, changed content-type to "application/x-www-form-urlencoded" in Sender.

  2. Changed string str = Request.Params["username"]; to string str = Request.Form["username"]; or string str = Request["username"]; in Receiver.

I hope they will work in your application as well.