【问题标题】:How to send xml through an HTTP request, and receive it using ASP.NET MVC?如何通过 HTTP 请求发送 xml,并使用 ASP.NET MVC 接收它?
【发布时间】:2013-08-19 18:47:56
【问题描述】:

我正在尝试通过 HTTP 请求发送一个 xml 字符串,并在另一端接收它。在接收端,我总是知道 xml 为空。你能告诉我这是为什么吗?

发送:

    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, 0, 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);
}

【问题讨论】:

    标签: c# asp.net-mvc-4 post httprequest


    【解决方案1】:

    我能够像这样工作:

    [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作为参数不起作用。

    【讨论】:

    • 谢谢它也对我有用.. 如果您将其作为流发布,则必须读取输入流以获取数据。要在“xml”变量中接收,您必须将其与查询字符串一起发送为发布参数
    【解决方案2】:

    我相信这是因为您指定了req.ContentType = "text/xml";

    如果我没记错的话,当您使用“原始”类型定义控制器时(string 在这里是“原始”类型)

    public ActionResult Index(string xml){}
    

    MVC 将尝试在查询字符串或发布的表单数据(html 输入字段)中查找xml。但是,如果您向服务器发送更复杂的内容,MVC 会将其包装在特定的类中。

    例如,当您将多个文件上传到服务器时,您可以在控制器中接受它们,如下所示

    public ActionResult Index(IEnumerable<HttpPostedFileBase> files){}
    

    所以我的猜测是您必须使用正确的类在控制器中接受text/xml 流。

    更新:

    似乎没有这样的类,因为您接受数据流(并且它不是来自输入元素)。您可以编写自己的模型绑定器来接受 xml 文档。请参阅下面的讨论。

    Reading text/xml into a ASP.MVC Controller

    How to pass XML as POST to an ActionResult in ASP MVC .NET

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 2011-03-03
      • 1970-01-01
      • 2014-02-24
      • 2013-09-29
      • 2018-06-23
      • 2013-03-12
      相关资源
      最近更新 更多