Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Based on this article, I understand you normally enable it via a call to MapHttpAttributeRoutes() prior to setting up your convention-based routes. But I'm guessing this is the MVC way - I need to know the equivalent for WebForms.

I currently use MapHttpRoute() to set up my convention-based routes, and I'd like to try out the attribute-based routing in WebAPI2. I have updated my project with WebAPI2 - I just need to know how to enable the attribute-based routing feature.

Any info would be appreciated.

like image 495
kman Avatar asked Jan 15 '14 19:01

kman


1 Answers

You need not do anything special in case of WebForms. Web API attribute routing should work just as in MVC.

If you are using VS 2013, you can test this easily by create a project using "Web Forms" template and then choose "Web API" check 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's RouteConfig

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}
like image 128
Kiran Avatar answered Oct 22 '22 17:10

Kiran