Unit Testing Web API Controllers with Headers

I couldn’t find a good example of how to unit test a controller with

[code langauge=”csharp”] var headerValue = Request.Headers.GetValues("HEADER");[/code]

in the controller. Not too common, but happens enough it can be expected. Also the controller inheirts “ApiController” which doesn’t inheirt from “ControllerBase” so the usual controller context call won’t work.

Here is how I coded the unit test

[code language=”csharp”]
var config = new HttpConfiguration();
//add in the actual route or method if your are looking at it in your code
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/random");
//DefaultApi maps to your web api route setup
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
//add in the extra data, similar to when you call @Url.Route
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
var controller = new MyProject.Controllers.Api.ExampleController();
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Headers.Add("X-Your-Header","HeaderValue");
[/code]

In the controller, do a

[code langauge=”csharp”] var headerValue = Request.Headers.GetValues("HEADER");[/code]

do not do

[code langauge=”csharp”]
//DON’T DO THIS
var headerValue = HttpContext.Current.Request.Headers.GetValues("HEADER");[/code]

This will hit the old IIS style objects and your unit test will fail.

If you don’t have Resharper, you might need these using statements.

[code langauge=”csharp”]

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *