Reputation: 40062
In my attempt to learn and understand WebAPI I think I have learnt that returns from APIController methods are wrapped up into HttpResponseMessage.
You also have the option to create a new HttpResponseMessage and put your List<Product>
inside it.
I am interested in testing headers for example and if I pass in a accept header with the below code I want to test for the content type returned in the response.
I know I can always return a HttpResponseMessage because strictly thats what its doing but I was just wondering if there was a way to either cast the response back from a controller method as a HttpResponseMessage without having to create a HttpServer/HttpConfiguration setup as shown here.
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/products");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var route = config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}"
);
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "GetData" } });
var controller = new GetDataController();
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
/************************* HELP!!!***************/
// If Get returns List<Product> can I cast it as HttpResponseMessage??
/************************************************/
var result = controller.Get();
// Assert
Assert.Equal("application/json", result.Content.Headers.ContentType.MediaType);
Upvotes: 0
Views: 1713
Reputation: 22392
Controller methods are not meant to be called directly like that. You have to send an HTTP request to get an HTTP response. Try using
HttpResponseMessage response = HttpClient.SendAsync(request).Result;
Although if you are not hosting in IIS you would have to create an HttpSelfHostServer
to host the controller inside the process so that it can listen for requests. This will show you how to do that, http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api
Upvotes: 2