AttributeRouting with IHttpControllerSelector - Api Versioning

I am trying to reach api versions using CustomHttpControlSelector and AttributeRouting on asp.net webapi.

What I'm trying to do is distinguish controller versions from namespaces.

if the request is made / api / v 2 / foo / bar I want it to match

namespace Web.Controllers.Api.v2
{
    [RoutePrefix("foo")]
    public class LongerThanFooController : ApiController
    {
        [HttpGet]
        [Route("bar")]
        public string BarFunction()
        {
            return "foobar";
        }
    }
}

but, as I see it, when I do not use the full url in RoutePrefix (/ api / v2 / foo), the attribute routing does not work, and I get null when called

 request.GetRouteData().GetSubRoutes();

on my CustomHttpControlSelector. I do not want to repeat / api / v 2 on each controller.

if I decide to remove the Routing attribute and use manual routes, for example

 config.Routes.MapHttpRoute(
         name: "DefaultVersionedApi",
         routeTemplate: "api/v{version}/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
 );

 config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional, version = Config.LatestVersion }
  );

I lose all flexibility in the name of my controllers and functions.

Is there any way out of this uncertainty?

note: CustomHttpControlSelector http://aspnet.codeplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs

+4

Source: https://habr.com/ru/post/1616414/


All Articles