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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With