Enable web api attribute routing in global.asax

I would like to enable Attribute Routing for the web API as it seems to simplify the definition of routing. An example here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 shows how this is done in the WebApiConfig.cs file :

using System.Web.Http; namespace WebApplication { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); // Other Web API configuration not shown. } } } 

However, my project is an old web form project, originally launched in .Net 2.0 (now it's 4.5 after several updates over the years). I don't have a WebApiConfig.cs file, and instead, my current routes are determined directly in the global.asax Application_Start method, using:

 RouteTable.Routes.MapHttpRoute(...) 

Can someone explain the best way to enable attribute based routing in this situation? Thanks

+5
source share
2 answers

You can just do GlobalConfiguration.Configuration.MapHttpAttributeRoutes(); in your Global.asax file.

GlobalConfiguration.Configuration object is passed to the WebApiConfig file, so you can use this class to configure everything you need in Global.asax

+10
source

You must put these 2 lines before the route definitions, and it will work with pleasure

  GlobalConfiguration.Configuration.MapHttpAttributeRoutes(); GlobalConfiguration.Configuration.EnsureInitialized(); 

Greetings

+3
source

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


All Articles