在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON [英] Using WebAPI or MVC to return JSON in ASP.NET

查看:21
本文介绍了在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

My understanding is both Web API Controller and MVC Controller can return JSON.

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

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

推荐答案

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

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.)

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

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.

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

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.

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

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.

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

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.

这篇关于在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆