在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10346342/
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-03 18:18:18  来源:igfitidea点击:

Using WebAPI or MVC to return JSON in ASP.NET

jsonasp.net-mvcasp.net-web-api

提问by Nil Pun

I'm building an ASP.NET MVC application that is client-script heavy, it will use JSON and jQuery to manipulate the DOM.

我正在构建一个客户端脚本繁重的 ASP.NET MVC 应用程序,它将使用 JSON 和 jQuery 来操作 DOM。

My understanding is both Web API Controllerand MVC Controllercan return JSON.

我的理解是Web API ControllerMVC Controller都可以返回 JSON。

Given my scenario, should I use a Web API Controlleror an MVC Controller?

鉴于我的情况,我应该使用Web API 控制器还是MVC 控制器

回答by Shaun Wilson

Web API Controllers can be created and hosted in any ASP.NET Application, not just MVC applications. Thus, an obvious reason to create a Web API is if you do not have an MVC front-end (e.g. classic, RESTful web-services hosted by your company/organization.)

Web API 控制器可以在任何 ASP.NET 应用程序中创建和托管,而不仅仅是 MVC 应用程序。因此,创建 Web API 的一个明显原因是,如果您没有 MVC 前端(例如,由您的公司/组织托管的经典的 RESTful Web 服务)。

MVC Controllers typically rely on the MVC Framework, if you look at default templates and most of the work done by the community and your peers you will notice that almost all MVC Controllers are implemented with the View in mind.

MVC 控制器通常依赖于 MVC 框架,如果您查看默认模板以及社区和同行完成的大部分工作,您会注意到几乎所有 MVC 控制器都是在实现视图的情况下实现的。

Personally, I use MVC Controllers when I intend to respond with a View(), and I'll use a Web API for anything that isn't dependent on a particular view.

就我个人而言,当我打算使用 View() 进行响应时,我会使用 MVC 控制器,并且对于不依赖于特定视图的任何内容,我都会使用 Web API。

There are caveats, of course, but generally speaking if you don't require the Model Binding behavior of MVC, your service is data-centric, and operations are Data-centric (e.g. CRUD operations) then you likely want a 'Web API Controller' instead of a 'Model-View Controller'. Conversely, if your operations are View-centric (e.g. delivering a user admin page to the user), or you need MVC's Model Binding to generate 'ajax partials' (very unlikely), then you will want an MVC Controller instead.

当然,有一些警告,但一般来说,如果您不需要 MVC 的模型绑定行为,您的服务以数据为中心,并且操作以数据为中心(例如 CRUD 操作),那么您可能需要一个“Web API 控制器” ' 而不是 'Model-View Controller'。相反,如果您的操作以视图为中心(例如向用户提供用户管理页面),或者您需要 MVC 的模型绑定来生成“ajax 部分”(非常不可能),那么您将需要一个 MVC 控制器。

Personally, I use Web API controllers for driving JSON-based RESTful clients, I use MVC controllers for handling basic browser routing and delivery of the SPA.

就我个人而言,我使用 Web API 控制器来驱动基于 JSON 的 RESTful 客户端,我使用 MVC 控制器来处理基本的浏览器路由和 SPA 的交付。

回答by Muhammad Hasan Khan

WebAPI is for making an API. If you want someone to be able to consume your API in XML, JSON, etc. You can make a web api.

WebAPI 用于制作 API。如果您希望有人能够以 XML、JSON 等形式使用您的 API,您可以制作一个 Web api。

In your case you only need to talk to client in JSON.

在您的情况下,您只需要在 JSON 中与客户端交谈。

Even though your website is mostly client script driven you would still be using ASP.NET MVC Controller right? And since you may have already logically divided your controllers based on entities then it make sense to add those json serving methods in it as opposed to making another class specifically for web api.

即使您的网站主要是客户端脚本驱动的,您仍然会使用 ASP.NET MVC 控制器,对吗?并且由于您可能已经根据实体在逻辑上划分了您的控制器,因此在其中添加那些 json 服务方法而不是专门为 web api 制作另一个类是有意义的。

So for your particular situation (if i understand correctly), I would stick with Controllers.

因此,对于您的特定情况(如果我理解正确的话),我会坚持使用控制器。

回答by Kris

The answer boils down to separation of concerns, fasten the creation of services and to rely on convention rather than configuration.

答案归结为关注点分离、加快服务的创建以及依赖约定而不是配置。

Controllers main responsibility is to work as a coordinator between view and your model but where as API's main responsibility is to work on data. In the case of API's conventions make it really easy to perform CRUD operations. Below is the mapping between CRUD operation and HTTP actions

控制器的主要职责是作为视图和模型之间的协调器,但 API 的主要职责是处理数据。在 API 约定的情况下,执行 CRUD 操作非常容易。下面是CRUD操作和HTTP动作的映射

  • GET : Read
  • POST: Create
  • PUT: Update
  • DELETE: Delete
  • 获取:阅读
  • POST:创建
  • PUT:更新
  • 删除:删除

So with APIs you do not have to create separate actions and attribute them with HTTP actions.

因此,使用 API,您不必创建单独的操作并将它们归于 HTTP 操作。

回答by Ramon Chan

The only concern I have with ApiController is that it is site-based not area-based. One site can only have one apicontroller subfolder for you to name your controller methods. There are situations you might want to duplicate controller name in different areas :

我对 ApiController 唯一的担忧是它基于站点而不是基于区域。一个站点只能有一个 apicontroller 子文件夹供您命名控制器方法。在某些情况下,您可能希望在不同区域复制控制器名称:

domain.com/api/area1/controller1/

domain.com/api/area1/controller1/

domain.com/api/area2/controller1/

domain.com/api/area2/controller1/

I remember there are some custom code settings to be able to do this but it does not work by default.

我记得有一些自定义代码设置可以做到这一点,但默认情况下它不起作用。

回答by R.H. Thorne

I agree with Shaun Wilson's (top answer) answer but not sure why as I am just a bit confused and still trying to understand with the following (probably incorrect) premonition -

我同意肖恩威尔逊(最佳答案)的答案,但不知道为什么,因为我有点困惑,并且仍在试图理解以下(可能不正确的)预感 -

  • Use WebAPI Controller to deliver JSON data to the client so that the client can handle the view manipulation. This process doe NOT require a view but rather just a response back to whatever called the method (i.e. a javascript request) so that the client can handle any client-side manipulation.
  • Use MVC controller when you need to use the data to manipulate a view during or right after page_load (i.e. not for SPA apps).
  • 使用 WebAPI Controller 将 JSON 数据传递给客户端,以便客户端可以处理视图操作。此过程不需要视图,而只需要对调用该方法的任何内容(即 javascript 请求)的响应,以便客户端可以处理任何客户端操作。
  • 当您需要在 page_load 期间或之后使用数据操作视图时,请使用 MVC 控制器(即不适用于 SPA 应用程序)。

You see, I just don't know how I am incorrect here and am confused because the last line of Shaun's answer states "I use MVC controllers for handling basic browser routing and delivery of the SPA." - perhaps I do not fully know what a restful client is when I assumed it could be JavaScript method that receives an response in JSON form. this is the closest post in Stackoverflow that was remotely related as an answer to my question so I'm answering this post instead of possibly duplicating questions.

你看,我只是不知道我在这里怎么不正确并且很困惑,因为肖恩回答的最后一行指出“我使用 MVC 控制器来处理基本的浏览器路由和 SPA 的交付。” - 当我假设它可能是接收 JSON 格式响应的 JavaScript 方法时,也许我不完全知道什么是 Restful 客户端。这是 Stackoverflow 中最接近的帖子,与我的问题的答案有很大关系,所以我正在回答这篇文章,而不是可能重复的问题。

回答by jezzipin

In this scenario, I would recommend WebApi as it's perfect for transferring data such as this based upon Javascript requests. I will usually develop my WebApi controllers so that they return a JSON friendly object that can then be parsed easily by my Javascript.

在这种情况下,我会推荐 WebApi,因为它非常适合根据 Javascript 请求传输此类数据。我通常会开发我的 WebApi 控制器,以便它们返回一个 JSON 友好的对象,然后可以通过我的 Javascript 轻松解析。

The only real time where you would want to use an action on an MVC controller for this sort of thing would be if you wanted to generate some HTML and replace segments of your page with Javascript calls.

您希望在 MVC 控制器上对此类事情使用操作的唯一实时情况是,如果您想生成一些 HTML 并用 Javascript 调用替换您的页面部分。

For example:

例如:

You have a JQuery UI Datepicker that upon selection generates a list of radio buttons that represent events on the chosen day.

您有一个 JQuery UI Datepicker,它在选择时会生成一个单选按钮列表,这些按钮代表所选日期的事件。

In this scenario, you could use WebApi to return some JSON and then generate the necessary HTML using Javascript but generally it's bad practise to create a lot of HTML using Javascript. It would be much better to have C# build up the HTML and then return it via a partial view as this way you are less likely to encounter errors with Javascript parsing. Not to mention it makes the HTML a lot easier to write.

在这种情况下,您可以使用 WebApi 返回一些 JSON,然后使用 Javascript 生成必要的 HTML,但通常使用 Javascript 创建大量 HTML 是不好的做法。让 C# 构建 HTML 然后通过部分视图返回它会更好,因为这样您不太可能遇到 Javascript 解析错误。更不用说它使 HTML 更容易编写。