Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to have a console application to send a XML file to a web application developed in ASP.NET MVC 3, and receive another XML as a response.

The error returned in the console application is:

The remote server returned an error: (500) Internal Server Error.

When I get Fiddler2 running, I see this error:

Object reference not set to an instance of an object.

The code in the console application is:

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();
}

The code in the MVC Controller is:

[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 the file via form (in a method with the same name, using method GET). RunTest() returns the XML with the response.

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

How do I fix that? What do I have to change in my console application for it to actually send a file? Or is it the case to 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.

like image 786
Lucas Reis Avatar asked Apr 03 '12 22:04

Lucas Reis


People also ask

How can upload file in ASP.NET MVC?

Uploading a file in Asp.Net MVC application is very easy. The posted file is automatically available as a HttpPostedFileBase parameters in the action of the controller. For uploading a file on the server you required to have a file input control within html form having encoding type set to multipart/form-data.


1 Answers

Your problem is that WebClient.UploadFile isn't posting a form with the enctype set to multipart/form-data using an input named "file" for MVC to map to. Try changing your server side method to this:

[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");
}
like image 183
Chris Avatar answered Oct 20 '22 20:10

Chris