Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Controller Method -- Request is null

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.

like image 944
Thomas McNamee Avatar asked Jan 12 '23 23:01

Thomas McNamee


1 Answers

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);
like image 105
Thomas McNamee Avatar answered Jan 22 '23 01:01

Thomas McNamee