您可以将 WebApi 2 的基于属性的路由与 WebForms 一起使用吗? [英] Can you use the attribute-based routing of WebApi 2 with WebForms?

查看:16
本文介绍了您可以将 WebApi 2 的基于属性的路由与 WebForms 一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想知道您是否可以将 WebAPI 2 的基于属性的路由与 WebForms 结合使用.我觉得这显然可以做到,因为您可以在 WebForms 应用程序中很好地使用 WebAPI2……我只是不知道如何启用基于属性的路由.

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.

基于这个 文章,我了解您通常在设置基于约定的路由之前通过调用 MapHttpAttributeRoutes() 启用它.但我猜这是 MVC 方式 - 我需要知道 WebForms 的等价物.

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.

我目前使用 MapHttpRoute() 来设置我的基于约定的路由,我想在 WebAPI2 中尝试基于属性的路由.我已经使用 WebAPI2 更新了我的项目 - 我只需要知道如何启用基于属性的路由功能.

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.

任何信息将不胜感激.

推荐答案

对于 WebForms,您不需要做任何特殊的事情.Web API 属性路由应该像在 MVC 中一样工作.

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

如果您使用的是 VS 2013,您可以通过使用Web 表单"模板创建一个项目,然后选择Web API"复选框来轻松测试这一点,您应该会看到由此生成的所有以下代码.

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 的 RouteConfig

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

这篇关于您可以将 WebApi 2 的基于属性的路由与 WebForms 一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆