unable to read values from Request.Params in c#

2019-08-11 02:26发布

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:

enter image description here

Any idea, what is going wrong?

3条回答
放我归山
2楼-- · 2019-08-11 02:39

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
查看更多
Melony?
3楼-- · 2019-08-11 02:40

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-08-11 02:42

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

查看更多
登录 后发表回答