How to upload a file to ASP.NET MVC from a console application

I am trying to have a console application to send an XML file to a web application developed in ASP.NET MVC 3 and get another XML as a response.

Error in console application:

The remote server responded with an error: (500) Internal server error.

When I run Fiddler2, I see this error:

The reference to the object is not installed in the instance of the object.

Code in console application:

static void Main(string[] args) { var wc = new WebClient(); byte[] response = wc.UploadFile("http://mysite.com/Tests/Test", "POST", "teste.xml"); string s = System.Text.Encoding.ASCII.GetString(response); Console.WriteLine(s); Console.ReadKey(); } 

Code in MVC:

 [HttpPost] public ActionResult Test(HttpPostedFileBase file) { XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream)); var test = new MyTest(); return File(test.RunTest(xml), "text/xml", "testresult.xml"); } 

RunTest() works well, since this method works when I upload a file through a form (in a method with the same name, using the GET method). RunTest() returns the XML with the response.

When I debug an MVC application, I see a problem: the file variable is null!

How to fix it? What do I need to change in my console application so that it really sends the file? Or can this change the MVC method?

And, before trying to use WebClient , I tried this code here: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx and had the same results.

+6
source share
3 answers

Your problem is that WebClient.UploadFile does not submit the form with enctype set to multipart / form-data, using the input named "file" for MVC to map. Try changing your server side method:

 [HttpPost] public ActionResult Test() { var file = Request.Files[0] as HttpPostedFile; XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream)); var test = new MyTest(); return File(test.RunTest(xml), "text/xml", "testresult.xml"); } 
+6
source

You need to pass a name for the parameter with the downloaded file. This is not possible with WebClient.

Check

How to specify a form parameter when using the web client to upload a file

Send a content type request for data of type multipart / form-data

0
source

If someone has a slightly different but related issue:

I also had to do this using the UploadData function instead of UploadFile . In this case, instead of writing to the controller:

 var file = Request.Files[0] as HttpPostedFile; XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream)); 

You can simply write:

 XElement xml = XElement.Load(new System.IO.StreamReader(Request.InputStream)); 

Easier!;)

0
source

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


All Articles