本文翻译自: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,我现在看到两种类型的控制器: ApiControllerController

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. 从现在我们可以使用两个控制器可以有人请指出在哪种情况下去相应的控制器。


#1楼

参考:https://stackoom.com/question/dq4c/ASP-NET-MVC中ApiController与Controller的区别


#2楼

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<Tweet> Get() {return Twitter.GetTweets();}
}

#3楼

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: 为此,您需要执行以下操作:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost . 使用NuGet安装以下Web API包: Microsoft.AspNet.WebApi.CoreMicrosoft.AspNet.WebApi.WebHost
  • Add one or more ApiControllers to your /Controllers/ folder. 将一个或多个ApiControllers添加到/Controllers/文件夹。
  • Add the following WebApiConfig.cs file to your /App_Config/ folder: 将以下WebApiConfig.cs文件添加到/App_Config/文件夹:

using System.Web.Http;public static class WebApiConfig
{public static void Register(HttpConfiguration config){// Web API routesconfig.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.csGlobal.asax.cs ,具体取决于您是否使用OWIN Startup模板)。

Startup.cs Startup.cs

 public void Configuration(IAppBuilder app){// Register Web API routing support before anything elseGlobalConfiguration.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 elseGlobalConfiguration.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. 我在博客上写的这篇文章进一步解释了这种方法及其优缺点。


#4楼

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打包。


#5楼

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你可以在同一个程序中使用你需要的


#6楼

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平台。

ASP.NET MVC中ApiController与Controller的区别相关推荐

  1. ASP.NET MVC中controller和view相互传值的方式

    ASP.NET MVC中Controller向view传值的方式: ViewBag.ViewData.TempData 单个值的传递 Json 匿名类型 ExpandoObject Cookie Vi ...

  2. 通过源代码研究ASP.NET MVC中的Controller和View(二)

    通过源代码研究ASP.NET MVC中的Controller和View(一) 在开始之前,先来温习下上一篇文章中的结论(推论): IView是所有HTML视图的抽象 ActionResult是Cont ...

  3. 在ASP.NET MVC 中获取当前URL、controller、action

    在ASP.NET MVC 中获取当前URL.controller.action URL的获取很简单,ASP.NET通用: [1]获取 完整url  (协议名+域名+虚拟目录名+文件名+参数) stri ...

  4. [转载]Asp.net MVC中Controller返回值类型

    Asp.net MVC中Controller返回值类型 在mvc中所有的controller类都必须使用"Controller"后缀来命名 并且对Action也有一定的要求: 必须 ...

  5. 通过源代码研究ASP.NET MVC中的Controller和View(三)

    通过源代码研究ASP.NET MVC中的Controller和View(一) 通过源代码研究ASP.NET MVC中的Controller和View(二) 第三篇来了,上一篇我已经把VirtualPa ...

  6. 【转载】ASP.NET MVC中Controller与View之间的数据传递总结

    在ASP.NET MVC中,经常会在Controller与View之间传递数据,因此,熟练.灵活的掌握这两层之间的数据传递方法就非常重要.本文从两个方面进行探讨: Ø Controller向View传 ...

  7. 如何在 ASP.NET MVC 中集成 AngularJS(3)

    今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...

  8. 3分钟学会在 ASP.NET MVC 中创建、读取和编辑 Excel 电子表格

    在本文中,您将学习如何在ASP.NET MVC 应用程序中创建.读取和编辑 Excel 电子表格.为此,我们将创建一个由功能丰富的网格控件组成的电子表格应用程序,用于显示和编辑 Excel 文件,如下 ...

  9. 从零开始学习 ASP.NET MVC 1.0 (三) Controller/Action 深入解析与应用实例 【转】

    一.摘要 一个Url请求经过了Routing处理后会调用Controller的Action方法. 中间的过程是怎样的? Action方法中返回ActionResult对象后,如何到达View的? 本文 ...

最新文章

  1. Auto Machine Learning 自动化机器学习笔记
  2. java comet_用java实现comet,基于 HTTP长连接的实现,用于从服务端实时发送信息到客户端...
  3. 数字类型的不正确转换漏洞
  4. oracle找到表的位置,查看Oracle表中的指定记录在数据文件中的位置
  5. 正式请求:Could you...? May I...? _52
  6. iOS逆向工程- 工具详解
  7. 操作系统原理(二)操作系统逻辑结构、CPU的态和中断机制
  8. Windows 平台下安装Cygwin后,sshd服务无法启动
  9. Axure RP 9的安装与汉化
  10. 细胞穿膜肽( CPPs)偶联肽核酸H region-PNA|Arg-PNA|Lys-PNA|Cationic-PNA|47Tat57-PNA的特性
  11. 上古卷轴php代码,【上古卷轴五木柴代码】
  12. 怎么把录音转文字?只需三步,手把手教会你
  13. 教学打铃单片机实现(课程设计)
  14. werfault.exe出现的原因与解决办法
  15. 七牛云绑定阿里云域名
  16. 解决Python官网打不开
  17. 用事实说话,成熟的ORM性能不是瓶颈,灵活性不是问题:EF5.0、PDF.NET5.0、Dapper...
  18. 工信部成立12321垃圾信息举报中心
  19. C++无法打开源文件
  20. android蓝牙获取mac地址,如何获得蓝牙连接设备的MAC地址在android中

热门文章

  1. Linux开机报write same failed manually zeroing错误
  2. 3.0-rsync格式
  3. Android学习2--项目文件列表简单分析
  4. apache 建立用户认证
  5. P3146 [USACO16OPEN]248 P3147 [USACO16OPEN]262144
  6. C语言指针类型 强制转换
  7. 函数(定义、参数、return、变量、作用域、预解析)
  8. Windows 键盘快捷键概述
  9. win10无法新建文件夹怎么办 win10右键新建菜单设置方法
  10. (转) Lua: 给 Redis 用户的入门指导