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!