Can you use attribute-based WebApi 2 routing with WebForms?

As the title says, I'm wondering if you can use attribute-based WebAPI 2 routing with WebForms. I feel this can obviously be done, since you can use WebAPI2 just in a WebForms application ... I just can't figure out how to enable attribute-based routing.

Based on this article, I understand that you usually enable it by calling MapHttpAttributeRoutes () before setting up convention-based routes. But I guess this is the MVC path - I need to know the equivalent for WebForms.

I am currently using MapHttpRoute () to configure convention-based routes, and I would like to try attribute-based routing in WebAPI2. I updated my project using WebAPI2 - I just need to know how to enable the attribute-based routing function.

Any information would be appreciated.

+4
source share
1 answer

You do not need to do anything special with WebForms. Web API attribute routing should work just like MVC.

If you are using VS 2013, you can easily test this by creating a project using the Web Forms template, then check the Web API box and you should see all the following code generated by this.

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Global.asax

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

WebForm RouteConfig

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}
+7

All Articles