4

调用如下所示的方法时,Request 始终为 null。我有一些简单的方法从 MVC4 应用程序中的控制器返回 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();

谢谢你的帮助。

4

1 回答 1

9

Olav Nybø 给我留下了导致答案的提示。为了响应使用 Request.CreateResponse 进行 ASP.NET WebApi 单元测试,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);
于 2013-11-08T01:02:38.097 回答