API method web API. The request is zero.

When invoking the method shown below, Request is always null. I have some simple methods that return JSON data from controllers in an MVC4 application with controllers using ApiController as a base class. The code for my catalog function is as follows:

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);
        }
    }

When this method is called, 'dir' is loaded properly from r.GetDirectory (). But Request is null. Therefore, naturally, Request.CreateResponse () fails and so on. I'm looking for reasons why Request will be null, or for a rewrite that allows the return to remain HttpResponseMessage.

This is called (in my unit test project) with:

var ctrl = new DirectoryController();
var httpDir = ctrl.GetDirectory();

Thank you for your help.

+4
1
, . ASP.NET WebApi 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);
+8