6

When calling the method shown below, Request is always null. I have some simple methods returning JSON data from controllers in an MVC4 app with controllers using ApiController as a base class. The code for my directory 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. So naturally Request.CreateResponse() fails, and so on. I am looking for reasons why Request would be null, or for a rewrite that allows the return to remain an HttpResponseMessage.

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

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

Thanks for your help.

Thomas McNamee
  • 692
  • 1
  • 6
  • 14
  • 1
    Is it only in your unit test that request is null? If this is the case you may find some useful information here: http://stackoverflow.com/questions/10868673/asp-net-webapi-unit-testing-with-request-createresponse – Olav Nybø Nov 07 '13 at 18:36

1 Answers1

11

Olav Nybø left me the hint that led to the answer. In response to ASP.NET WebApi unit testing with Request.CreateResponse, jonnii suggested the following code:

        controller.Request = new HttpRequestMessage();
        controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

This led to a nice way to test controllers:

        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);
Community
  • 1
  • 1
Thomas McNamee
  • 692
  • 1
  • 6
  • 14