How to send data to an MVC controller using HttpWebRequest?

I am trying to send data to an MVC controller, but have not been successful so far.

Here is the message data structure:

private string makeHttpPostString(XmlDocument interchangeFile) { string postDataString = "uid={0}&localization={1}&label={2}&interchangeDocument={3}"; InterchangeDocument interchangeDocument = new InterchangeDocument(interchangeFile); using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { interchangeFile.WriteTo(xmlTextWriter); string interchangeXml = HttpUtility.UrlEncode(stringWriter.GetStringBuilder().ToString()); string hwid = interchangeDocument.DocumentKey.Hwid; string localization = interchangeDocument.DocumentKey.Localization.ToString(); string label = ConfigurationManager.AppSettings["PreviewLabel"]; return (string.Format(postDataString, hwid, localization, label, interchangeXml)); } } 

Here is the request:

  HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(controllerUrl); webRequest.Method = "POST"; // webRequest.ContentType = "application/x-www-form-urlencoded"; string postData = makeHttpPostString(interchangeFile); byte[] byteArray = Encoding.UTF8.GetBytes(postData); webRequest.ContentLength = byteArray.Length; using (Stream dataStream = webRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } HttpWebResponse webresponse = (HttpWebResponse) webRequest.GetResponse(); 

When I set the request content type to "application / x-www-form-urlencoded" GetReponse () fails with a 500 server error code. When I comment on this and only httpencode the xml data, "interchangeXml", the message is sent, but only the third parameter, "label" reaches the controller. The rest are null.

What is the correct way to send values ​​to a controller action when one of these values ​​is xml data?

Thanks!

Update

I am sending the entire parameter except XML via the query string. However, the problem now is that I do not know how to access published data in the controller action. Can someone tell me how I access xml from HttpRequest from my controller action?

Update

I reworked the code above to use the suggestions Darin made to me. I get an internal server error (500) using WebClient UploadValues ​​().

Act:

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult BuildPreview(PreviewViewModel model) { ... } 

Inquiry:

 private string PostToSxController(XmlDocument interchangeFile, string controllerUrl) { var xmlInterchange = new InterchangeDocument(interchangeFile); using (var client = new WebClient()) { var values = new NameValueCollection() { {"uid", xmlInterchange.DocumentKey.Hwid}, {"localization", xmlInterchange.DocumentKey.Localization.ToString()}, {"label", ConfigurationManager.AppSettings["PreviewLabel"]}, {"interchangeDocument", interchangeFile.OuterXml } }; byte[] result = null; try { result = client.UploadValues(controllerUrl, values); } catch(WebException ex) { var errorResponse = ex.Response; var errorMessage = ex.Message; } Encoding encoding = Encoding.UTF8; return encoding.GetString(result); } } 

Route:

 routes.MapRoute( "BuildPreview", "SymptomTopics/BuildPreview/{model}", new { controller = "SymptomTopics", action = "BuildPreview", model = UrlParameter.Optional } ); 
+6
source share
3 answers

Too complex and insecure client code with all these requests and responses. You do not encode any parameters of your request, let alone XML, which is likely to break everything if you do not encode it properly.

For this reason, I would simplify and leave the plumbing coding code, etc. in the .NET platform:

 using (var client = new WebClient()) { var values = new NameValueCollection { { "uid", hwid }, { "localization", localization }, { "label", label }, { "interchangeDocument", interchangeFile.OuterXml }, }; var result = client.UploadValues(controllerUrl, values); // TODO: do something with the results returned by the controller action } 

As for the server side, as for each correctly created ASP.NET MVC application, it will obviously use a view model:

 public class MyViewModel { public string Uid { get; set; } public string Localization { get; set; } public string Label { get; set; } public string InterchangeDocument { get; set; } } 

from:

 [HttpPost] public ActionResult Foo(MyViewModel model) { // TODO: do something with the values here ... } 

Obviously, this can be done even further by writing a presentation model that reflects the structure of your XML document:

 public class Foo { public string Bar { get; set; } public string Baz { get; set; } } 

and then your model will look like this:

 public class MyViewModel { public string Uid { get; set; } public string Localization { get; set; } public string Label { get; set; } public Foo InterchangeDocument { get; set; } } 

and the last part is to write a custom binder for type Foo , which will use an XML serializer (or something else) to deserialize the InterchangeDocument POSTed value to an instance of Foo . Now this is a serious business.

+12
source

I am struggling with the same beast here: Attempting to configure controller action as an Xml endpoint

Perhaps you are getting an internal server error, because either you have a page check (solution: addotate with ValidateInput (false)), or you are not sending an Accept-Encoding header with your request. I would love to hear how I can get MVC to accept published data without the Accept-Encoding HTTP header ...

+1
source

I just found that you can call the controller, even its dependency, even from Web Forms code for help with the Nuget "T4MVC" package:

https://github.com/T4MVC/T4MVC

0
source

Source: https://habr.com/ru/post/889993/


All Articles