How to upload a file to ASP.NET MVC from a console application
asp.net-mvc-3, c#, console-application, file-upload, webclient
Solution
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");
}
Problem
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.