我试图通过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作为参数不起作用.