我有一个 ASP.NET MVC 3 控制器操作。该动作定义如下:
[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);
}
我需要通过 C# 应用程序上传到此端点。目前,我正在使用以下内容:
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
}
虽然我得到 200,但状态始终是“错误”。进一步挖掘后,我注意到 parameter1 始终为空。我有点困惑。有人可以告诉我如何通过 WebRequest 以编程方式发送参数 1 的数据以及代码中的文件吗?
谢谢!