c# – 如何通过HTTP请求发送xml,并使用ASP.NET MVC接收它?

前端之家收集整理的这篇文章主要介绍了c# – 如何通过HTTP请求发送xml,并使用ASP.NET MVC接收它?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图通过HTTP请求发送一个xml字符串,并在另一端接收它.在接收端,我总是得到xml为null.你能告诉我为什么会这样吗?

发送:

var url = "http://website.com";
    var postData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><xml>...</xml>";
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);

    var req = (HttpWebRequest)WebRequest.Create(url);

    req.ContentType = "text/xml";
    req.Method = "POST";
    req.ContentLength = bytes.Length;

    using (Stream os = req.GetRequestStream())
    {
        os.Write(bytes,bytes.Length);
    }

    string response = "";

    using (System.Net.WebResponse resp = req.GetResponse())
    {
        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            response = sr.ReadToEnd().Trim();
        }
     }

接收:

[HttpPost]
[ValidateInput(false)]
public ActionResult Index(string xml)
{
    //xml is always null
    ...
    return View(model);
}

解决方法

我能够这样工作:
[HttpPost]
[ValidateInput(false)]
public ActionResult Index()
{
    string xml = "";
    if(Request.InputStream != null){
        StreamReader stream = new StreamReader(Request.InputStream);
        string x = stream.ReadToEnd();
        xml = HttpUtility.UrlDecode(x);
    }
    ...
    return View(model);
}

但是,我仍然很好奇为什么将xml作为参数不起作用.

猜你在找的C#相关文章