正如标题所述,我想知道您是否可以将WebAPI 2的基于属性的路由与WebForms一起使用。 我觉得这显然是可以做到的,因为您可以在 WebForms 应用程序中很好地使用 WebAPI2...... 我只是不知道如何启用基于属性的路由。
基于本文,我知道您通常在设置基于约定的路由之前通过调用 MapHttpAttributeRoutes() 来启用它。 但我猜这是MVC的方式 - 我需要知道WebForms的等效物。
我目前使用 MapHttpRoute() 来设置基于约定的路由,我想在 WebAPI2 中尝试基于属性的路由。 我已经使用 WebAPI2 更新了我的项目 - 我只需要知道如何启用基于属性的路由功能。
任何信息将不胜感激。
在WebForms的情况下,你不需要做任何特别的事情。Web API 属性路由应该像在 MVC 中一样工作。
如果您使用的是VS 2013,则可以通过使用"Web Forms"模板创建项目,然后选择"Web API"复选框来轻松测试它,您应该会看到由此生成的所有以下代码。
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 }
);
}
}
全球
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);
}
}