本文翻译自:Difference between ApiController and Controller in ASP.NET MVC
I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiController
and Controller
. 我一直在玩ASP.NET MVC 4 beta,我现在看到两种类型的控制器: ApiController
和Controller
。
I'm little confused at what situations I can choose a particular controller. 我对可以选择特定控制器的情况感到困惑。
For ex: If I want to return a view then I've to use ApiController
or the ordinary Controller
? 例如:如果我想返回一个视图,那么我将使用ApiController
或普通的Controller
? I'm aware that the WCF Web API is now integrated with MVC. 我知道WCF Web API现在已与MVC集成。
Since now we can use both controllers can somebody please point at which situations to go for the corresponding controller. 从现在我们可以使用两个控制器可以有人请指出在哪种情况下去相应的控制器。
参考:https://stackoom.com/question/dq4c/ASP-NET-MVC中ApiController与Controller的区别
Which would you rather write and maintain? 你宁愿写作和维护哪个?
ASP.NET MVC ASP.NET MVC
public class TweetsController : Controller {
// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
ASP.NET Web API ASP.NET Web API
public class TweetsController : ApiController {
// GET: /Api/Tweets/
public List Get() {
return Twitter.GetTweets();
}
}
I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. 我喜欢ASP.NET Core的MVC6将这两种模式合并为一种这一事实,因为我经常需要支持这两种模式。 While it's true that you can tweak any standard MVC Controller
(and/or develop your own ActionResult
classes) to act & behave just like an ApiController
, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult
mixed with others returning raw/serialized/ IHttpActionResult
data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach. 虽然你可以调整任何标准MVC Controller
(和/或开发自己的ActionResult
类)来行动和行为就像ApiController
,但是维护和测试很难:最重要的是,让Controllers方法返回ActionResult
与其他人混合返回raw / serialized / IHttpActionResult
数据从开发人员的角度来看可能非常混乱,特别是如果你不是单独工作并且需要让其他开发人员加快这种混合方法的速度。
The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers
for Views, ApiControllers
for data. 到目前为止,我在ASP.NET非核心Web应用程序中最小化该问题的最佳技术是将Web API包导入(并正确配置)到基于MVC的Web应用程序中,因此我可以充分利用这两者worlds:视图Controllers
,数据ApiControllers
。
In order to do that, you need to do the following: 为此,您需要执行以下操作:
Microsoft.AspNet.WebApi.Core
and Microsoft.AspNet.WebApi.WebHost
. 使用NuGet安装以下Web API包: Microsoft.AspNet.WebApi.Core
和Microsoft.AspNet.WebApi.WebHost
。 /Controllers/
folder. 将一个或多个ApiControllers添加到/Controllers/
文件夹。 /App_Config/
folder: 将以下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 }
);
}
}
Finally, you'll need to register the above class to your Startup class (either Startup.cs
or Global.asax.cs
, depending if you're using OWIN Startup template or not). 最后,您需要将上述类注册到Startup类( Startup.cs
或Global.asax.cs
,具体取决于您是否使用OWIN Startup模板)。
Startup.cs 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 的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 approach - together with its pros and cons - is further explained in this post I wrote on my blog. 我在博客上写的这篇文章进一步解释了这种方法及其优缺点。
Every method in Web API will return data (JSON) without serialization. Web API中的每个方法都将返回数据(JSON)而不进行序列化。
However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON. 但是,为了在MVC控制器中返回JSON数据,我们将返回的Action Result类型设置为JsonResult并在对象上调用Json方法以确保它以JSON打包。
It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. 在两者之间做出决定相当简单:如果你正在编写一个基于HTML的web / internet / intranet应用程序 - 可能偶尔会在这里和那里返回json的AJAX调用 - 坚持使用MVC / Controller。 If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. 如果要为系统提供数据驱动/ REST-ful接口,请使用WebAPI。 You can combine both, of course, having an ApiController cater AJAX calls from an MVC page. 当然,您可以将两者结合起来,从MVC页面获得ApiController来处理AJAX调用。 Basically controller is use for mvc and api-controller is use for Rest- API you can use both in same program as your need 基本上控制器用于mvc和api-controller用于Rest- API你可以在同一个程序中使用你需要的
The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. 主要区别在于:Web API是任何客户端,任何设备的服务,而MVC Controller仅为其客户端提供服务。 The same because it is MVC platform. 同样因为它是MVC平台。