博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC中ApiController与Controller的区别
阅读量:3579 次
发布时间:2019-05-20

本文共 5901 字,大约阅读时间需要 19 分钟。

本文翻译自:

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楼

参考:


#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
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 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.csGlobal.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 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平台。

转载地址:http://gllgj.baihongyu.com/

你可能感兴趣的文章
数据结构 c++实现顺序表的基本操作/初始化/输入/输出/插入/删除
查看>>
JavaScript中alert和console.log的区别
查看>>
IDEA 编译 JS 无法使用require 下面有波浪线
查看>>
微信小程序之官方UI框架 iView UI 之 Grid宫格布局
查看>>
微信小程序———点击屏幕涟漪效果
查看>>
webstorm /Intellij IDEA/PHPstorm/Pyhcarm破解方法
查看>>
VSvode如何使用git bash 设置linux终端命令 Windows下使用vim
查看>>
Acrobat Pro DC破解安装
查看>>
vi/vim怎么显示行数
查看>>
Node学习基础(二) express和module.express区别
查看>>
Node学习基础之安装node以及配置环境变量
查看>>
Node学习基础(一) 之了解nodejs
查看>>
Node学习基础(三) 之文件的同步和异步写入操作(fs_文件系统)
查看>>
Node学习基础(四)之文件的流操作以及pipe管道简单举例
查看>>
自定义安装mysql
查看>>
bootstrap配置
查看>>
修改MySQL数据库密码
查看>>
Navicat Premium 12破解
查看>>
html中的data-reactid属性是什么?
查看>>
浅谈一个不常用的html标签fieldset
查看>>