Ambiguous Controller Names with Routing attributes: controllers with same name and different namespace for versioning

前端 未结 3 1848
迷失自我
迷失自我 2020-12-15 06:39

I am trying to add API versioning and my plan is to create a controller for each version in different namespace. My project structure looks like this (note: no separate area

3条回答
  •  独厮守ぢ
    2020-12-15 07:01

    First, Web API routing, and MVC routing doesn't work exactly in the same way.

    Your first link points to MVC routing, with areas. Areas are not officially supported for Web API, although you can try to make something similar to them. However, even if you try to do something like that, you'll get the same error, because the way in wich Web API looks for a controller doesn't takes into account the controller's namespace.

    So, out of the box, it will never work.

    However, you can modify most Web API behaviors, and this is not an exception.

    Web API uses a Controller Selector to get the desired controller. The behavior explained above is the behavior of the DefaultHttpControllerSelector, which comes with Web API, but you can implement your own selector to replace the default one, and support new behaviors.

    If you google for "custom web api controller selector" you'll find many samples, but I find this the most interesting for exactly your problem:

    • ASP.NET Web API: Using Namespaces to Version Web APIs

    This implementation is also interesting:

    • https://github.com/WebApiContrib/WebAPIContrib/pull/111/files (thank you to Robin van der Knaap for the update of this broken link)

    As you see there, basically you need to:

    • implement your own IHttpControllerSelector, which takes into account namespaces to find the controllers, and the namespaces route variable, to choose one of them.
    • replace the original selector with this via Web API configuration.

提交回复
热议问题