0
votes

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);
1
Are you trying create an integration test by creating a standalone server and sending an actual HTTP request as Despertar suggests or are you creating a unit test to check your controller code directly?Sixto Saez
Well I was hoping I could make it so that it can be called and get a valid HTTP response back without a HttpServerJon
You'll need a running instance of the controller then as Despertar is suggesting.Sixto Saez
Because responses are only populated properly when invoked by a valid HTTP Request?Jon

1 Answers

2
votes

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