ASP.NET Core 中文文档 第四章 MVC(4.1)Controllers, Actions 和 Action Results

原文:Controllers, Actions, and Action Results
作者:Steve Smith
翻译:姚阿勇(Dr.Yao)
校对:许登洋(Seay)

Action 和 action result 是开发者使用 ASP.NET MVC 构建应用程序的基础部分。

什么是 Controller

在 ASP.NET MVC 中, 控制器( Controller
 )用于定义和聚合操作(Action)的一个集合。操作( 或操作方法 )是控制器中处理入站请求的一个方法。控制器提供了一种逻辑方式将相似的操作组织起来,允许一些通用的规则(如:路由,缓存和验证)得到共同的应用。 入站请求通过路由(routing)被映射到操作上。

在 ASP.NET Core MVC 中,控制器可以是任何以 “Controller” 结尾或者继承自以 “Controller” 结尾的可实例化类。控制器应当遵循 显式依赖原则 并且通过使用依赖注入在构造函数中获取他们需要的任何依赖项。

按照惯例,控制器类:

  • 放在根目录下的 “Controllers” 文件夹中
  • 继承自 Microsoft.AspNetCore.Mvc.Controller

这两个惯例不是强制要求。

在模型-视图-控制器模式中,控制器负责初始化请求以及实例化模型。通常来说,业务流程应当放在模型中执行。

说明
模型应该是一个简单的传统 CLR 对象(Plain Old CLR Object (POCO) ),而不是一个数据库上下文 DbContext 或者关系数据库类型。

控制器取得模型的执行结果(如果有),返回正确的视图以及相关的视图数据。更多请参考:Overview of ASP.NET Core MVC 和 ASP.NET Core MVC 和 Visual Studio 入门

技巧
控制器是一个 UI级别 的抽象。它的责任在于确保入站请求的数据是有效的,然后选择应当返回哪一个视图(或者 API 的结果)。在有着良好分解的应用程序中,控制器不会直接包含数据访问或业务逻辑,而是委托给服务去处理这些任务。

Action 的定义

控制器上的任意公共方法都是一个 Action 。Action 上的参数是通过 模型绑定 来请求数据绑定并校验。

提示
带有参数的 Action 方法应该检查 ModelState.IsValid 属性的值是否为真 。

Action 方法应当包含将传入请求映射到业务的逻辑。业务关注通常应该表现为由控制器通过( 依赖注入(dependency injection))访问服务。Actions 然后映射业务行为的结果到应用程序的状态。

Action 可以返回任何东西,但是常常会返回一个 IActionResult (或异步方法返回的 Task<IActionResult> )实例生成响应。Action 方法负责选择“响应的类型”,Action Result 负责“响应的执行”。

控制器辅助方法

  • 视图(View)
    返回一个使用模型渲染 HTML 的视图。例: return View(customer);
  • HTTP 状态代码
    返回一个 HTTP 状态代码。例: return BadRequest();
  • 格式化的响应
    返回 Json 或类似以特定方式格式化的对象。例: return Json(customer);
  • 内容协商的响应
    除了直接返回一个对象,Action 还可以返回一个内容协商的响应(使用 OkCreated,CreatedAtRoute 或 CreatedAtAction )。例如:return Ok();  或 return CreatedAtRoute("routename",values,newobject");
  • 重定向
    返回一个指向其他 Action 或目标的重定向(使用 Redirect,LocalRedirect,RedirectToAction 或 RedirectToRoute )。例如: return RedirectToAction("Complete", new {id = 123});

除了上面的方法之外,Action 还可以直接返回一个对象。在这种情况下,对象将以客户端要求的方式进行格式化。详情请参考: 格式化响应数据

横切关注点

在大多数应用中,许多 Action 会共用部分工作流。例如,大多数应用可能只对验证过的用户开放,或者要利用缓存。当你想要在 Action 方法运行之前或之后执行一些逻辑业务时,可以使用 过滤器(filter) 。利用 过滤器(filters) 处理一些横切关注点,可以防止你的 Action 变得过于臃肿。这有助于剔除 Action 中的重复代码,使得它们可以遵循 不要重复你自己(DRY)原则 。

就验证和授权而言,你可以将 Authorize 特性应用在任何一个要求授权的 Action 上。将它加在控制器上将会对该控制器里的所有的 Action 采用授权。这个特性的添加将确保每个访问此 Action 的请求都被应用了对应的过滤器。有些特性可以同时应用在控制器和 Action 上,以提供对过滤器行为更小粒度的控制。

关于 MVC 应用程序中横切关注点的其他例子:

提示
在 MVC 应用程序里,很多横切关注点都可以利用过滤器来处理。还有另一种对所有 ASP.NET Core 应用程序都有效的选择需要记住,就是自定义 中间件(middleware)

返回目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET Core 1.1 For Beginners: How to Build a MVC Website by Jonas Fagerberg English | 19 May 2017 | ASIN: B071VX7KN4 | 411 Pages | PDF | 6.66 MB Want to learn how to build ASP.NET Core 1.1 MVC Web Applications? Prerequisites: * C# (Intermediate level) * HTML5/CSS3 (Basic knowledge) This book is primarily aimed at developers who want to learn how to build ASP.NET Core 1.1 MVC Applications. You should be an intermediate level C# developer with some experience in HTML5 and CSS3. The book presupposes that you have a solid C# foundation since the language won't be explained in any detail. You will learn ASP.NET Core 1.1 by building two MVC applications. The first application will be built using an empty template. The goal is to get you familiar with ASP.NET Core 1.1 by adding middleware and services one piece at a time, building a basic application. Then you will build a second MVC application using a template that already contains support for MVC, Entity Framework Core, and user authentication. This application is a video course website, where users can register to gain access to video courses. If you are already familiar with MVC 5, the content in this book can get you started with ASP.NET Core 1.1 in a fast, no-fluff way. It's important to mention that this book is practical and tactical, where you will learn as you progress through the modules and build real web applications in the process. To spare you countless pages of fluff (filler material), only valuable information, pertinent to the task at hand, is discussed. The benefit is a shorter and more condensed book, which will save you time and give you a more enjoyable experience. The goal is to learn ASP.NET Core 1.1 by building two web applications, one from scratch and one from an existing template. This experience is something you can put in your CV when applying for a job or a consultant position, or when negotiating a higher salary. Technologies, frameworks and languages you will use: * ASP.NET Core 1.1 MVC (The framework that you will use) * Services (To provide you own functionality as a reusable service) * Middleware (To provide you own functionality to HTTP Request pipeline) * Entity Framework (To crate and communicate with a database) * View Component (To render data in the _Layout view with model data) * Razor syntax (To include server-side code in views) * Bootstrap (Used for styling and to create a responsive design) * LINQ (To query the database) * Dependency Injection (To inject objects into constructors) * Tag Helper (to clean up the HTML and enable re-use) * HTML Helper methods (to clean up your HTML and enable re-use) * Bower/NuGet (To install necessary front-end/back-end libraries) What you will implement: * Implement a web application from an empty template. * Implement a web application from an existing template. * Create a "real world" code-first database using Entity Framework Core. * Add and modify models, views and controllers to perform CRUD operations against the database. * Use client-side and server-side validation. * Secure the controllers, actions and view content with authorization and roles. * Styling HTML with CSS and Bootstrap. * Create a responsive website. * Register users with the site. * Manage users and their video courses.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值