我喜欢 ASP.NET Core 的 MVC6 将这两种模式合二为一,因为我经常需要同时支持这两种模式。虽然您确实可以调整任何标准 MVC Controller(和/或开发自己的 ActionResult 类)以像 ApiController 一样操作和表现,但它可能很难维护和测试:在顶部也就是说,从开发人员的角度来看,将返回 ActionResult 的 Controllers 方法与返回原始/序列化/IHttpActionResult 数据的其他方法混合在一起可能会非常令人困惑,特别是如果您不是一个人工作并且需要携带其他开发人员可以加快使用这种混合方法的速度。
到目前为止,为了最大限度地减少 ASP.NET 非核心 Web 应用程序中的该问题,我采用的最佳技术是将 Web API 包导入(并正确配置)到基于 MVC 的 Web 应用程序中,这样我就可以拥有两全其美:Controllers 用于查看,ApiControllers 用于数据。
为此,您需要执行以下操作:
- 使用 NuGet 安装以下 Web API 包:
Microsoft.AspNet.WebApi.Core 和 Microsoft.AspNet.WebApi.WebHost。
- 将一个或多个 ApiController 添加到您的
/Controllers/ 文件夹。
- 将以下 WebApiConfig.cs 文件添加到您的
/App_Config/ 文件夹:
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
最后,您需要将上述类注册到您的 Startup 类(Startup.cs 或 Global.asax.cs,取决于您是否使用 OWIN Startup 模板)。
Startup.cs
public void Configuration(IAppBuilder app)
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureAuth(app);
// ...
}
Global.asax.cs
protected void Application_Start()
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// ...
}
我在博客上写的this post 进一步解释了这种方法及其优缺点。