asp.net-mvc ASP.NET MVC 中 ApiController 和 Controller 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9494966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:46:34  来源:igfitidea点击:

Difference between ApiController and Controller in ASP.NET MVC

asp.net-mvcasp.net-web-api

提问by VJAI

I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiControllerand 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 ApiControlleror the ordinary Controller? I'm aware that the WCF Web API is now integrated with MVC.

例如:如果我想返回一个视图,那么我必须使用ApiController还是普通的Controller?我知道 WCF Web API 现在已与 MVC 集成。

Since now we can use both controllers can somebody please point at which situations to go for the corresponding controller.

由于现在我们可以同时使用两个控制器,有人可以指出在哪些情况下使用相应的控制器。

回答by Andre Loker

Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.

使用 Controller 渲染您的普通视图。ApiController 操作仅返回序列化并发送到客户端的数据。

here is the link

链接在这里

Quote:

引用:

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

注意 如果您使用过 ASP.NET MVC,那么您已经熟悉控制器。它们在 Web API 中的工作方式类似,但 Web API 中的控制器派生自 ApiController 类而不是 Controller 类。您会注意到的第一个主要区别是 Web API 控制器上的操作不返回视图,它们返回数据。

ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.

ApiControllers 专门用于返回数据。例如,它们负责将数据透明地序列化为客户端请求的格式。此外,它们默认遵循不同的路由方案(如:将 URL 映射到操作),按照惯例提供 REST-ful API。

You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.

您可能可以使用 Controller 而不是 ApiController 和 some(?) 手动编码来做任何事情。最后,这两个控制器都建立在 ASP.NET 基础之上。但是拥有 REST-ful API 在今天是如此普遍,以至于创建 WebAPI 是为了简化此类 API 的实现。

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. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.

在两者之间做出决定相当简单:如果您正在编写基于 HTML 的 web/internet/intranet 应用程序 - 可能偶尔会在这里和那里返回 json 的 AJAX 调用 - 坚持使用 MVC/Controller。如果您想为系统提供数据驱动/REST-ful 接口,请使用 WebAPI。当然,您可以将两者结合起来,让 ApiController 提供来自 MVC 页面的 AJAX 调用。

To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.

举一个真实的例子:我目前正在使用一个 ERP 系统,该系统为其实体提供 REST-ful API。对于这个 API,WebAPI 将是一个很好的候选者。同时,ERP 系统提供了一个高度 AJAX 化的 Web 应用程序,您可以使用它来为 REST-ful API 创建查询。Web 应用程序本身可以实现为 MVC 应用程序,利用 WebAPI 获取元数据等。

回答by Manish Jain

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();
  }
}

回答by Darkseal

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller(and/or develop your own ActionResultclasses) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllersmethods returning ActionResultmixed with others returning raw/serialized/IHttpActionResultdata 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.

我喜欢 ASP.NET Core 的 MVC6 将这两种模式合二为一的事实,因为我经常需要同时支持这两种模式。虽然这是真的,你可以调整任何标准的MVC Controller(和/或开发自己的ActionResult类)采取行动和表现就像是一个ApiController,也可以是非常难以维护和测试:最重要的是,其控制器方法返回ActionResult与他人混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: Controllersfor Views, ApiControllersfor 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.Coreand Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/folder.
  • Add the following WebApiConfig.csfile to your /App_Config/folder:
  • 使用 NuGet 安装以下 Web API 包:Microsoft.AspNet.WebApi.CoreMicrosoft.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 }
        );
    }
}

Finally, you'll need to register the above class to your Startupclass (either Startup.csor Global.asax.cs, depending if you're using OWIN Startup template or not).

最后,您需要将上述类注册到您的Startup类(Startup.cs或者Global.asax.cs,取决于您是否使用 OWIN 启动模板)。

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 postI wrote on my blog.

我在博客上写的这篇文章中进一步解释了这种方法及其优缺点。

回答by Shailesh Uke

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 中。

回答by ANJYR - KODEXPRESSION

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.

主要区别在于:Web API 是针对任何客户端、任何设备的服务,而 MVC Controller 仅为其客户端提供服务。一样,因为它是MVC平台。

回答by ANJYR - KODEXPRESSION

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. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page. Basically controller is use for mvc and api-controller is use for Rest- API you can use both in same program as your need

在两者之间做出决定相当简单:如果您正在编写基于 HTML 的 web/internet/intranet 应用程序 - 可能偶尔会在这里和那里返回 json 的 AJAX 调用 - 坚持使用 MVC/Controller。如果您想为系统提供数据驱动/REST-ful 接口,请使用 WebAPI。当然,您可以将两者结合起来,让 ApiController 提供来自 MVC 页面的 AJAX 调用。基本上控制器用于 mvc,而 api-controller 用于 Rest-API,您可以根据需要在同一个程序中使用它们