无法从c#中的Request.Params读取值

时间:2015-10-14 08:57:07

标签: c# httpwebrequest saml saml-2.0

我有以下一段代码让我无法阅读Request.Params的值。现在我只想读取我从发件人传递的值(在收件人中),即用户名和SAMLResponse。

发件人

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

接收方

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

错误

enter image description here

任何想法,出了什么问题?

3 个答案:

答案 0 :(得分:0)

你可以改变这一行:

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

到此:

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

给我们一个结果?

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

答案 1 :(得分:0)

我发现您的代码存在一些问题。

  1. 编码 - 您应该在执行obj.ToString()时对XML文件进行编码,因为它可能包含会混淆事物的字符。
  2. 内容类型 - 您告诉接收者您正在发送XML,但您实际上是在发送表单。因此,您应将内容类型设置为application/x-www-form-urlencoded

答案 2 :(得分:0)

这适用于我的应用程序。

  1. 正如其他回答者所说,在发件人中将内容类型更改为"application/x-www-form-urlencoded"

  2. 接收器中将string str = Request.Params["username"];更改为string str = Request.Form["username"];string str = Request["username"];

  3. 我希望他们也能在您的申请中使用。