调用下面显示的方法时,Request始终为null。我有一些简单的方法从MVC4 app中的控制器返回JSON数据,控制器使用ApiController作为基类。我的目录函数的代码如下:
public HttpResponseMessage GetDirectory() {
try {
var dir = r.GetDirectory();
if (dir == null) {
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
var response = Request.CreateResponse(HttpStatusCode.OK, dir, "application/json");
response.Headers.Location = new Uri(Request.RequestUri, "directory");
return response;
} catch (Exception ex) {
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
调用此方法时,从r.GetDirectory()正确加载'dir'。但请求为空。所以Request.CreateResponse()自然会失败,等等。我正在寻找Request为null的原因,或者为了允许返回仍为HttpResponseMessage的重写。
这个(在我的单元测试项目中)被调用:
var ctrl = new DirectoryController();
var httpDir = ctrl.GetDirectory();
感谢您的帮助。
答案 0 :(得分:8)
OlavNybø给我留下了导致答案的暗示。为回应ASP.NET WebApi unit testing with Request.CreateResponse,jonnii建议使用以下代码:
controller.Request = new HttpRequestMessage();
controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
这导致了一种测试控制器的好方法:
var controller = new RecordsController();
controller.Request = new HttpRequestMessage();
controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
var json = controller.GetAllRecords(id);
var records = JsonConvert.DeserializeObject<DynamicRecordSet>(json.Content.ReadAsStringAsync().Result);