Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable web api attribute routing in global.asax

I'd like to enable Attribute Routing for Web API as it looks like it will make routing easier to define. The example here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 shows how it 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 forms project, originally started in .Net 2.0 (it's now 4.5 following several upgrades over the years). I don't have a WebApiConfig.cs file and instead my current routes are defined directly in the global.asax Application_Start method using:

RouteTable.Routes.MapHttpRoute(...)

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

like image 735
Kate Avatar asked Dec 03 '14 14:12

Kate


People also ask

How do I enable routing in Web API?

The Route attribute can be applied on any controller or action method. In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config. MapHttpAttributeRoutes() method.

How do I register a route in global ASAX?

We register routes in the Global. asax file and we invoke a RegisterRoutes method in the Application_Start() method. Routing is used to create user friendly URLs. It can also be used to setup the startup page of the application, just like the ASP.NET Web Forms.

What is attribute routing in Web API?

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

How do I set the default route in .NET core Web API?

Right click your web project -> Select Properties -> Select the Debug tab on the left -> Then edit the 'Launch Url' field to set your own default launch url. Great!


2 Answers

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

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

like image 192
Vsevolod Goloviznin Avatar answered Sep 21 '22 22:09

Vsevolod Goloviznin


You should put these 2 lines before your route definitions and it will work happily

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

Cheers

like image 32
user3578181 Avatar answered Sep 20 '22 22:09

user3578181