I have an ASP.NET MVC 3 controller action. That action is defined as follows:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string parameter1, HttpPostedFileBase uploadFile)
{
if (parameter1 == null)
return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);
if (uploadFile.ContentLength == 0)
return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);
return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet);
}
I need to upload to this endpoint via a C# app. Currently, I’m using the following:
public void Upload()
{
WebRequest request = HttpWebRequest.Create("http://www.mydomain.com/myendpoint");
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.BeginGetRequestStream(new AsyncCallback(UploadBeginGetRequestStreamCallBack), request);
}
private void UploadBeginGetRequestStreamCallBack(IAsyncResult ar)
{
string json = "{\"parameter1\":\"test\"}";
HttpWebRequest webRequest = (HttpWebRequest)(ar.AsyncState);
using (Stream postStream = webRequest.EndGetRequestStream(ar))
{
byte[] byteArray = Encoding.UTF8.GetBytes(json);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
}
webRequest.BeginGetResponse(new AsyncCallback(Upload_Completed), webRequest);
}
private void Upload_Completed(IAsyncResult result)
{
WebRequest request = (WebRequest)(result.AsyncState);
WebResponse response = request.EndGetResponse(result);
// Parse response
}
While I get a 200, the status is always “Error”. After digging further, I noticed that parameter1 is always null. I’m slightly confused. Can somebody please tell me how to programmatically send data for parameter1 as well as a file from code via a WebRequest?
Thank you!
Dude, this one was difficult!
I really tried to find a way to programmatically upload files to a MVC action, but I couldn’t, I’m sorry.
The solution I found converts the file to a byte array and serializes it into a string.
Here, take a look.
This is your controller action:
And this is the client code (who posts the file):
Hanselman has a good post regarding file upload from a web interface, which is not your case.
If you need help to convert the byte array back to a file, check this thread: Can a Byte[] Array be written to a file in C#?
Hope this helps.
If anyone has a better solution, I’d like to take a look at it.
Regards,
Calil