If You Do .NET

Short description of the blog

How to unit test ASP.NET Web API 2 Route Attributes

Problem

What I thought was a simple search on the web turned out to be more than that.

The closets to a solution I found was from the person who first made it possible to use Attributes for routing in ASP.NET MVC 4: AttributeRouting not working with HttpConfiguration object for writing Integration tests

But what about ASP.NET Web Api 2?

HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes(); // This don't work. I guess there is needed some more plumbing to know what Controllers to search for attributes, but I'm lost here.
HttpServer server = new HttpServer(config);
 
using (HttpMessageInvoker client = new HttpMessageInvoker(server))
{
    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/accounts/10"))
    using(HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
    {
        response.StatusCode.Should().Be(HttpStatusCode.Created);
    }
}

The solution

So … what is the problem.

It turns of that I was missing a simple little line, just after the “config.MapHttpAttributes();”

config.EnsureInitialized();

So finally I got this working.

But why on earth does the HttpServer class or something else not ensure that the config have been initialized.

Why

So I was searching for a reason why this was needed and why this should actually be called.

If you decompile: System.Web.Http.GlobalConfiguration.Configure(Action<HttpConfiguration> configurationCallback)

You will get something like this:

public static void Configure(Action<HttpConfiguration> configurationCallback)
{
  if (configurationCallback == null)
    throw new ArgumentNullException("configurationCallback");
  configurationCallback(GlobalConfiguration.Configuration);
  GlobalConfiguration.Configuration.EnsureInitialized();
}

Why on earth is it done like that … for me this has absolutely nothing to do with “Ensure” … THIS needs to be called after all configuration is done.

Is can be called multiple times with no side effects.

Why ohhh why do you sometime hate us so much Microsoft. Winking smile

Avoid razor compile errors in MVC 4 when deploying

Yesterday I yet again experienced, that my MVC 4 build went fine when built and deployed using teamcity, but still a compile time bug sneaked into production.

Then a combination of google and talking to a friend led me to a solution. I short, this allows you to define that views should be compiled with certain targets. As compiling views increases the build time conciderably, you may want to avoid it for local development.

How to configure this is all shown here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=698