简体   繁体   English

ASP.NET MVC中ApiController和Controller的区别

[英]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.由于现在我们可以同时使用这两个控制器,有人可以指出在哪些情况下使用相应的控制器。

Use Controller to render your normal views.使用 Controller 渲染您的普通视图。 ApiController action only return data that is serialized and sent to the client. ApiController 操作仅返回序列化并发送到客户端的数据。

here is the link 链接在这里

Quote:引用:

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers.注意 如果您使用过 ASP.NET MVC,那么您已经熟悉控制器。 They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class.它们在 Web API 中的工作方式类似,但 Web API 中的控制器派生自 ApiController 类而不是 Controller 类。 The first major difference you will notice is that actions on Web API controllers do not return views, they return data.您会注意到的第一个主要区别是 Web API 控制器上的操作不返回视图,而是返回数据。

ApiControllers are specialized in returning data. ApiControllers 专门用于返回数据。 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.此外,它们默认遵循不同的路由方案(例如:将 URL 映射到操作),按照约定提供 REST-ful API。

You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding.您可能可以使用 Controller 而不是 ApiController 和 some(?) 手动编码来做任何事情。 In the end, both controllers build upon the ASP.NET foundation.最后,这两个控制器都建立在 ASP.NET 基础之上。 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.但如今,拥有一个 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.在两者之间做出决定相当简单:如果您正在编写基于 HTML 的 web/internet/intranet 应用程序 - 可能偶尔 AJAX 调用会在这里和那里返回 json - 坚持使用 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.当然,您可以将两者结合起来,让 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.举一个真实的例子:我目前正在使用一个 ERP 系统,该系统为其实体提供 REST-ful API。 For this API, WebAPI would be a good candidate.对于这个 API,WebAPI 将是一个不错的选择。 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.同时,ERP 系统提供了一个高度 AJAX 化的 Web 应用程序,您可以使用它来为 REST-ful API 创建查询。 The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc. Web 应用程序本身可以实现为 MVC 应用程序,利用 WebAPI 来获取元数据等。

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

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一样操作和行为,但维护和测试可能非常困难:除此之外,让Controller方法返回从开发人员的角度来看, 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: 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启动.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全球.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.我在博客上写的这篇文章进一步解释了这种方法及其优缺点。

Quick n Short Answer快速 n 简答

If you want to return a view, you should be in "Controller" .如果你想返回一个视图,你应该在"Controller"中。

Normal Controller - ASP.NET MVC: you deal with normal "Controller" if you are in ASP.net Web Application.普通控制器 - ASP.NET MVC:如果您在 ASP.NET Web 应用程序中,则处理普通的“控制器”。 You can create Controller-Actions and you can return Views().您可以创建 Controller-Actions 并且可以返回 Views()。

ApiController Controller: you create ApiControllers when you are developing ASP.net REST APIs. ApiController 控制器:在开发 ASP.net REST API 时创建 ApiController。 you can't return Views (though you can return Json/Data for HTML as string).您不能返回视图(尽管您可以将 HTML 的 Json/Data 作为字符串返回)。 These apis are considered as backend and their functions are called to return data not the view这些 api 被视为后端,它们的函数被调用以返回数据而不是视图

More Details here 更多细节在这里

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

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client.主要区别在于:Web API 是为任何客户端、任何设备提供的服务,而 MVC 控制器只为它的客户端服务。 The same because it is MVC platform.一样,因为它是 MVC 平台。

它几乎是一个,但是,MVC和API之间的名称,使用目的和透明度是不同的。

在此处输入图像描述

If you create a new web application in latest framework 4.7.2 you will both of them to be configured by default and can build you application on that如果您在最新的框架 4.7.2 中创建一个新的 Web 应用程序,您将默认配置它们,并且可以在该框架上构建您的应用程序

在此处输入图像描述

Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view. Asp.Net MVC 用于创建同时返回视图和数据的 Web 应用程序,但 Asp.Net Web API 用于创建完整的 HTTP 服务,其简单而简单的方式只返回数据,不返回视图。 Web API helps to build REST-ful services over the MVC only return data in JSON format using JsonResult. Web API 有助于在 MVC 上构建 REST-ful 服务,仅使用 JsonResult 以 JSON 格式返回数据。

Web API Controller: Web API 控制器:

//POST - Insert Data
    public IHttpActionResult PostNewCustomer(CustomerViewModel customer)
    {
        if (!ModelState.IsValid)
            return BadRequest("Invalid data. Please recheck1");
        using (var x=new WebAPIDemo_DBEntities())
        {
            x.customers.Add(new customer()
            {
                name = customer.Name,
                email = customer.Email,
                address = customer.Address,
                phone = customer.Phone
            });
            x.SaveChanges();
        }
        return Ok();

MVC Controller: MVC控制器:

    [HttpPost]
    public ActionResult Edit(CustomerMvcModel customer)
    {
        HttpResponseMessage response = GlobalVariables.webapiclient.PutAsJsonAsync("Customer/" + customer.Id, customer).Result;
        TempData["SuccessMessage"] = "Updated Successfully";
        return RedirectToAction("Index");
    }

Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view. Asp.Net MVC 用于创建同时返回视图和数据的 Web 应用程序,但 Asp.Net Web API 用于创建完整的 HTTP 服务,其简单而简单的方式只返回数据,不返回视图。 Web API helps to build REST-ful services over the MVC only return data in JSON format using JsonResult. Web API 有助于在 MVC 上构建 REST-ful 服务,仅使用 JsonResult 以 JSON 格式返回数据。 Example from my project: Web Api Controller: //POST - Insert Data public IHttpActionResult PostNewCustomer(CustomerViewModel customer) { if (!ModelState.IsValid) return BadRequest("Invalid data. Please recheck1");我的项目示例:Web Api 控制器://POST - 插入数据 public IHttpActionResult PostNewCustomer(CustomerViewModel customer) { if (!ModelState.IsValid) return BadRequest("Invalid data. Please recheck1"); using (var x=new WebAPIDemo_DBEntities()) { x.customers.Add(new customer() { name = customer.Name, email = customer.Email, address = customer.Address, phone = customer.Phone }); using (var x=new WebAPIDemo_DBEntities()) { x.customers.Add(new customer() { name = customer.Name, email = customer.Email, address = customer.Address, phone = customer.Phone }); x.SaveChanges(); x.SaveChanges(); } return Ok();返回 Ok(); MVC Controller: MVC控制器:

    [HttpPost]
    public ActionResult Edit(CustomerMvcModel customer)
    {
        HttpResponseMessage response = GlobalVariables.webapiclient.PutAsJsonAsync("Customer/" + customer.Id, customer).Result;
        TempData["SuccessMessage"] = "Updated Successfully";
        return RedirectToAction("Index");
    }

Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view. Asp.Net MVC 用于创建同时返回视图和数据的 Web 应用程序,但 Asp.Net Web API 用于创建完整的 HTTP 服务,其简单而简单的方式只返回数据,不返回视图。 Web API helps to build REST-ful services over the MVC only return data in JSON format using JsonResult. Web API 有助于在 MVC 上构建 REST-ful 服务,仅使用 JsonResult 以 JSON 格式返回数据。

Web Api Controller: //POST - Insert Data public IHttpActionResult PostNewCustomer(CustomerViewModel customer) { if (!ModelState.IsValid) return BadRequest("Invalid data. Please recheck1"); Web Api 控制器://POST - 插入数据 public IHttpActionResult PostNewCustomer(CustomerViewModel customer) { if (!ModelState.IsValid) return BadRequest("Invalid data. Please recheck1"); using (var x=new WebAPIDemo_DBEntities()) { x.customers.Add(new customer() { name = customer.Name, email = customer.Email, address = customer.Address, phone = customer.Phone }); using (var x=new WebAPIDemo_DBEntities()) { x.customers.Add(new customer() { name = customer.Name, email = customer.Email, address = customer.Address, phone = customer.Phone }); x.SaveChanges(); x.SaveChanges(); } return Ok();返回 Ok(); MVC Controller: MVC控制器:

[HttpPost]
public ActionResult Edit(CustomerMvcModel customer)
{
    HttpResponseMessage response = GlobalVariables.webapiclient.PutAsJsonAsync("Customer/" + customer.Id, customer).Result;
    TempData["SuccessMessage"] = "Updated Successfully";
    return RedirectToAction("Index");
}

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

In Asp.net Core 3+ Vesrion在 Asp.net Core 3+ 版本中

Controller : If wants to return anything related to IActionResult & Data also, go for Controller controller Controller :如果还想返回与 IActionResult & Data 相关的任何内容,请选择 Controller控制器

ApiController : Used as attribute/notation in API controller. ApiController :用作 API 控制器中的属性/符号。 That inherits ControllerBase Class继承 ControllerBase 类

ControllerBase : If wants to return data only go for ControllerBase class ControllerBase :如果想返回数据只去 ControllerBase 类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM