0
votes

I have a WebApi project based on WebApi v1 that uses the following for determining the version of the API to use...

    public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        var controllers = GetControllerMapping();
        var routeData = request.GetRouteData();
        var controllerName = (string)routeData.Values["controller"];
        HttpControllerDescriptor result = null;

        if (!controllers.TryGetValue(controllerName, out result))
        {
            string version;
            if (!GetVersionFromMediaType(request, out version))
            {
                if (!GetVersionFromAcceptHeaderVersion(request, out version))
                {
                    if (!GetVersionFromHeader(request, out version))
                    {
                        if (!GetVersionFromQueryString(request, out version))
                        {
                            version = LATEST_VERSION;
                        }
                    }
                }
            }

            HttpControllerDescriptor versionedDescriptor;

            var newName = string.Concat(controllerName, "V", version);
            if (controllers.TryGetValue(newName, out versionedDescriptor))
            {
                result = versionedDescriptor;
            }
        }

        return result;
    }

I'm knocking up a test using WebApi2 and I note that this process fails if I have defined my routes using Attribute Routing as request.GetRouteData() doesn't include any reference (that I can find) to the controller.

Does this mean that I am limited to versioning by including the version in the route itself?

1

1 Answers

0
votes

You can check my answer in the following post:

Versioning ASP.NET Web API 2 with Media Types

Also in soon to come release of Web API 2.1(assembly version 5.1.0.0), there is support for route-level constraints (note that this is different from 'inline' constraints that we already have) with which you can handle versioning scenarios. Of course, this is related to attribute routing only.

Following is a sample with 2.1 RC bits: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/RoutingConstraintsSample/ReadMe.txt