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
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.
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.
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.
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!
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
You should put these 2 lines before your route definitions and it will work happily
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.EnsureInitialized();
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With