我正在尝试将XML数据从一个MVC4服务器(服务器1)发送到另一个(服务器2)
以下简化代码。我的代码可以解决问题 - 调用服务器2方法,但数据似乎没有被传递。
任何想法我做错了(我认为问题的根源是我不理解如何正确转换xml数据以及服务器2应该如何接受它。)
我也尝试过使用client.UploadString
和WebRequest(我不想使用它,因为它看起来很麻烦)没有任何成功。
在服务器1中 - 用于将XML数据发送到server2
public void SubmitClicked(String answersJsonStr)
{
Debug.WriteLine("SubmitClicked() " + answersJsonStr);
XNode node = JsonConvert.DeserializeXNode(answersJsonStr, "Root");
var answersXml = node.ToString();
//This gives: "<Root>\r\n <question1>answer 1</question1>\r\n</Root>"
String fullUrl = "http://localhost:61728/SubmitSurveyAnswers";
WebClient client = new WebClient();
byte[] bret = client.UploadData(fullUrl, "POST",
System.Text.Encoding.ASCII.GetBytes(answersXml));
Debug.WriteLine(System.Text.Encoding.ASCII.GetString(bret));
}
server2中控制器中的方法
[HttpPost]
public ActionResult SubmitSurveyAnswers(String answersXml)
{
Debug.WriteLine("SubmitSurveyAnswers() " + answersXml);
//answersXML seems to be null
return Content("answers accepted", "text/html");
}
请注意,server2只是一个模拟模型 - XML的真正接收者将由另一家公司提供。
答案 0 :(得分:0)
您好像缺少内容类型标题
public void SubmitClicked(String answersJsonStr)
{
Debug.WriteLine("SubmitClicked() " + answersJsonStr);
XNode node = JsonConvert.DeserializeXNode(answersJsonStr, "Root");
var answersXml = node.ToString();
//This gives: "<Root>\r\n <question1>answer 1</question1>\r\n</Root>"
String fullUrl = "http://localhost:61728/SubmitSurveyAnswers";
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] bret = client.UploadData(fullUrl, "POST", System.Text.Encoding.ASCII.GetBytes(answersXml));
Debug.WriteLine(System.Text.Encoding.ASCII.GetString(bret));
}
}
答案 1 :(得分:0)
这似乎有用......
加入:“answersXml =”+ answersXml,
[ValidateInput(false)],
加上testydonkey的补充......
public void SubmitClicked(String answersJsonStr)
{
Debug.WriteLine("SubmitClicked() " + answersJsonStr);
XNode node = JsonConvert.DeserializeXNode(answersJsonStr, "Root");
var answersXml = node.ToString();
//This gives: "<Root>\r\n <question1>answer 1</question1>\r\n</Root>"
String fullUrl = "http://localhost:61728/SubmitSurveyAnswers";
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] bret = client.UploadData(fullUrl, "POST",
System.Text.Encoding.ASCII.GetBytes(("answersXml=" + answersXml)));
Debug.WriteLine(System.Text.Encoding.ASCII.GetString(bret));
}
}
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitSurveyAnswers(String answersXml)
{
Debug.WriteLine("SubmitSurveyAnswers() " + answersXml);
return Content("answers accepted ", "text/html");
}