2011-06-09 60 views
3

我想将一些数据发布到ASP.NET MVC Controller Action。目前我正在尝试使用WebClient.UploadData()将多个参数发布到我的操作中。如何在MVC Action中获取发布的数据?

以下操作将触发,但所有参数均为空。如何从http请求获取发布的数据?

string postFormat = "hwid={0}&label={1}&interchange={2}localization={3}"; 
var hwid = interchangeDocument.DocumentKey.Hwid; 
var interchange = HttpUtility.UrlEncode(sw.ToString()); 
var label = ConfigurationManager.AppSettings["PreviewLabel"]; 
var localization = interchangeDocument.DocumentKey.Localization.ToString(); 

string postData = string.Format(postFormat, hwid, interchange, label, localization); 

using(WebClient client = new WebClient()) 
{ 
    client.Encoding = Encoding.UTF8; 
    client.Credentials = CredentialCache.DefaultNetworkCredentials; 
    byte[] postArray = Encoding.ASCII.GetBytes(postData); 
    client.Headers.Add("Content-Type", "pplication/x-www-form-urlencoded"); 
    byte[] reponseArray = client.UploadData("http://localhost:6355/SymptomTopics/BuildPreview",postArray); 
    var result = Encoding.ASCII.GetString(reponseArray); 
    return result; 
} 

这里是我打电话

行动

公众的ActionResult BuildPreview(字符串HWID,串 标签,串交流,串 本地化){ ...}

当达到此操作时,所有参数都为空。

我已经尝试使用WebClient.UploadValue()并将数据作为NameValueCollection传递。这个方法总是返回一个500的状态,因为我在MVC应用程序中发出这个http请求,所以我找不到一个方法来调用它。

解决这个问题的任何帮助都会非常有帮助。

-Nick

我纠正了标题为:立即用

client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 

现在UploadData只是错误与服务器错误500

+0

获取原始发布字节内容类型看坏了。你在'pplication/x-www-form-urlencoded'的前面缺少'a'。 – 2011-06-09 02:52:53

+0

谢谢..所以当我纠正我的错误UploadData()只有错误500 – Nick 2011-06-09 03:04:08

+0

你有任何特殊的路线定义? – Jedidja 2011-06-09 04:28:09

回答

3

我能从Request对象的InputStream属性中获得后期xml数据。

 public ActionResult BuildPreview(string hwid, string label, string localization) 
     { 
      StreamReader streamReader = new StreamReader(Request.InputStream); 
      XmlDocument xmlDocument = new XmlDocument(); 
      xmlDocument.LoadXml(streamReader.ReadToEnd()); 
       ... 

} 
5

只是为了笑在Request.FormRouteData看看在你的控制器中查看是否有结果。

+0

这应该是被接受的答案 – Apolo 2014-07-15 10:27:28

+0

同意,应该是被接受的答案。这里是一个新手的例子:string somethingFromAField = Request.Form.Get(“someTextField”); - “someTextField”来自我们刚刚发送的表单 – jonprasetyo 2015-03-19 06:40:16

2

作为一种权宜之计,您可以随时将控制器操作更改为接受FormCollection参数,然后直接进入并访问表单参数。

0

WebClient.UploadData("http://somewhere/BuildPreview", bytes)

public ActionResult BuildPreview() 
{ 
    byte[] b; 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     Request.InputStream.CopyTo(ms); 
     b = ms.ToArray(); 
    } 

    ... 
} 
相关问题