views:

80

answers:

2

I need to run a Controller Action from my Console Application that reference to my MVC App.

The reason behind this is because there are some special Action method that i cannot just simply copy to the new application. (Because of the control things)

So I just want to ask if there could be any way to call a controller action method from the Console application? How could I send a file upload to the controller?

This is the example of my ActionResult that used to upload a file? how should i send the Request.Files to it?

  public ActionResult ImageUp(){
        foreach (string fname in Request.Files)
        {
            HttpPostedFileBase _file = Request.Files[fname];
        }
  }
A: 

System.Net.WebClient.UploadFile() can upload a file to a URL.

If you wanted to either upload multiple files, or to have other non-file parameters in the request, see the accepted answer to this question http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data

That said, a better solution would be to refactor ImageUp() into 2 methods - the first extracts the files from the HttpRequest, and the second acts on those files. The second method is then usable without a HttpContext, such as in a console app or unit test.

Lachlan Roche
A: 

I am pretty sure you can but it will take a bit of work to plug everything in correctly. You can create an instance of the controller class and call the ImageUp method from that instance. To setup the Request.Files correctly you will need to create your own instance of ControllerContext in order to push the values you want into Request.Files.

Matthew Manela