I am trying to post some data to a ASP.NET MVC Controller Action. Current I am trying to use WebClient.UploadData() to post several parameters to my action.
The following will hit the action but all the parameters are null. How can get the posted data from the http request?
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;
}
Here is the Action I am calling
public ActionResult BuildPreview(string hwid, string label, string interchange, string localization) { ... }
When this Action is reached all the parameters are null.
I have tried using th开发者_JAVA技巧e WebClient.UploadValue() and passing the data as a NameValueCollection. This method always returns a status of 500 and because I am making this http request from within the MVC application I cannot find a way to bebug this.
Any help getting this resolved would be super helpful.
-Nick
I corrected the Header to read:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
Now UploadData just errors immediately with with server error 500.
Just for laughs have a look in Request.Form
and the RouteData
in your controller to see if something ended up there.
I was able to get the post xml data from the Request objects InputStream property.
public ActionResult BuildPreview(string hwid, string label, string localization)
{
StreamReader streamReader = new StreamReader(Request.InputStream);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(streamReader.ReadToEnd());
...
}
As a stop-gap measure, you can always change your controller action to accept a FormCollection
parameter and then reach in and access the form parameters by name directly.
To get the raw posted bytes from WebClient.UploadData("http://somewhere/BuildPreview", bytes)
public ActionResult BuildPreview()
{
byte[] b;
using (MemoryStream ms = new MemoryStream())
{
Request.InputStream.CopyTo(ms);
b = ms.ToArray();
}
...
}
精彩评论