我正在使用以下方法通过ASP.NET Web API控制器上传文件。
[System.Web.Http.HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response;
try
{
int id = 0;
int? qId = null;
if (int.TryParse(HttpContext.Current.Request.Form["id"], out id))
{
qId = id;
}
var file = HttpContext.Current.Request.Files[0];
int filePursuitId = bl.UploadFile(qId, file);
}
catch (Exception ex)
{
}
return response;
}
在我的单元测试中,在调用UploadFile
操作之前,我手动创建了一个HTTPContext
类:
var request = new HttpRequest("", "http://localhost", "");
var context = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current = context;
response = controller.UploadFile();
很遗憾,由于Form
集合只读,我无法添加自定义值。同时,我也无法更改Files
集合。
在单元测试期间,是否有任何方法可以向Request
的Form
和Files
属性添加所需数据(id和文件内容)?