006.Adding a controller to a ASP.NET Core MVC app with Visual Studio -- 【在asp.net core mvc 中添加一个控制器】
索引:
Adding a controller to a ASP.NET Core MVC app with Visual Studio
在asp.net core mvc 中添加一个控制器
2017-2-28 5 分钟阅读时长
The Model-View-Controller (MVC) architectural pattern separates an app into three main components: Model, View, and Controller.
MVC结构模式将程序分割为三个组成部分:Model View Controller 。
The MVC pattern helps you create apps that are more testable and easier to update than traditional monolithic apps. MVC-based
相比于传统的一体式程序,MVC模式帮助你建立的程序,更加易于测试,升级。
apps contain:
基于MVC模式的程序包含:
- Models: Classes that represent the data of the app. The model classes use validation logic to enforce business rules for that
Models:用于表现app数据的类。模型类包含用于验证业务数据规则的逻辑。
data. Typically, model objects retrieve and store model state in a database. In this tutorial, a Movie model retrieves movie
典型的,模型对象存取DB中的数据。在本教程中, Movie 用来从DB中获取数据,
data from a database, provides it to the view or updates it. Updated data is written to a database.
提供给视图或用来做db更新。更新后的数据会被写入数据库。
- Views: Views are the components that display the app's user interface (UI). Generally, this UI displays the model data.
Views:视图是用来显示app ui的组件。通常,ui 显示模型中的数据。
- Controllers: Classes that handle browser requests. They retrieve model data and call view templates that return a response. In
Controllers:控制器是用来处理浏览器请求的类。它们获取model 中的数据并且处理视图模板并对浏览器做出一个响应。
an MVC app, the view only displays information; the controller handles and responds to user input and interaction. For
在mvc应用中,view仅用来显示信息用;controller处理并响应用户的输入与交互。
example, the controller handles route data and query-string values, and passes these values to the model. The model might
例如,控制器处理了路由数据与”?param=xxxx”此类数据,并将它们的值赋予model。
use these values to query the database. For example, http://localhost:1234/Home/About has route data of Home (the
model 可以使用这些数据来查询数据库。例如,http://localhost:1234/Home/About 含有路由数据,home(控制器),
controller) and About (the action method to call on the home controller). http://localhost:1234/Movies/Edit/5 is a
about(action方法)。http://localhost:1234/Movies/Edit/5 是一个
request to edit the movie with ID=5 using the movie controller. We'll talk about route data later in the tutorial.
请求编辑id=5的url。我们将在教程的后面讨论路由数据。
The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and UI logic),
MVC模式有助于我们建立的app关注并分离不同的方面点,如 输入逻辑,业务逻辑,UI逻辑,
while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the
它能在这些方面间提供一个松耦合的结构。Mvc模式特别指定了每种类型逻辑在app中的特定位置。
app. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation
UI逻辑属于视图。输入逻辑属于控制器。业务逻辑属于数据模型。
helps you manage complexity when you build an app, because it enables you to work on one aspect of the implementation at a
这种分离有助于你管理复杂的应用,因为它可以帮助你只关注一方面的实现而不用
time without impacting the code of another. For example, you can work on the view code without depending on the business logic
考虑另一个方面因素的影响。例如,你可以在视图上正常的书写调试代码而不必依赖于业务逻辑代码。
code.
We cover these concepts in this tutorial series and show you how to use them to build a movie app. The MVC project contains
这种概念贯穿于整个教程,并且将教会你如何利用它们构建一个 movie app。一个mvc项目包含
folders for the Controllers and Views. A Models folder will be added in a later step.
Controllers 和 Views 文件夹。Models 文件夹将在后面的步骤添加上。
- In Solution Explorer, right-click Controllers > Add > New Item
在资源管理器中,右击 Controllers > Add > New Item 菜单

- Select MVC Controller Class
选择 MVC Controller Class 选项
- In the Add New Item dialog, enter HelloWorldController.
在 Add New Item 对话框,输入 HelloWorldController 。

Replace the contents of Controllers/HelloWorldController.cs with the following:
在 Controllers/HelloWorldController.cs 中,输入以下代码:
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
}
C# code
Every public method in a controller is callable as an HTTP endpoint. In the sample above, both methods return a string. Note the
在控制器中每个被 public 修饰的方法都是可以被 http 请求的。在上面的例子中,两个方法都返回一个字符串。
comments preceding each method.
An HTTP endpoint is a targetable URL in the web application, such as http://localhost:1234/HelloWorld, and combines the
一个http 终点是一个可被命中的url 在浏览器中,如 http://localhost:1234/HelloWorld 这个url,
protocol used: HTTP, the network location of the web server (including the TCP port): localhost:1234 and the target
其中包含http协议前缀(http), 还包括 tcp地址 (localhost:1234) ,和 uri (HelloWorld) 。
URI HelloWorld.
The first comment states this is an HTTP GET method that is invoked by appending "/HelloWorld/" to the base URL. The second
第一个 注释 表示这个方法是一个 http get 方法,在基URL后加上 /HelloWorld/ 就可以被调用。第二个注释
comment specifies an HTTP GET method that is invoked by appending "/HelloWorld/Welcome/" to the URL. Later on in the tutorial
表示这也是一个 http get 方法,在基 URL 后加上 /HelloWorld/Welcome/ 就可以被调用。在本教程的后面部分
you'll use the scaffolding engine to generate HTTP POST methods.
你将学会用基架引擎来生产 http post 方法。
Run the app in non-debug mode and append "HelloWorld" to the path in the address bar. The Index method returns a string.
以非调试模式运行app并且在地址栏追加上 HelloWorld 。Index 方法将会被调用并返回一个字符串。

MVC invokes controller classes (and the action methods within them) depending on the incoming URL.
MVC 调用控制器类取决于请求过来的URL。
The default URL routing logic used by MVC uses a format like this to determine what code to invoke:
默认的URL路由规则由类似下面的格式决定了MVC怎样调用控制器代码:
/[Controller]/[ActionName]/[Parameters]
路由规则字符串
You set the format for routing in the Startup.cs file.
你需要在 Startup.cs 文件中,设置路由规则。
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
C# code
When you run the app and don't supply any URL segments, it defaults to the "Home" controller and the "Index" method specified in
当你运行app并且没有提供URL段,程序将默认调用 home控制器,并执行其中的index方法。
the template line highlighted above.
The first URL segment determines the controller class to run. So localhost:xxxx/HelloWorld maps to
第一个URL段决定了那个控制器类被执行。因此,localhost:xxxx/HelloWorld 将映射到
the HelloWorldController class. The second part of the URL segment determines the action method on the class.
HelloWorldController 这个控制器上。第二个URL段决定了控制器中哪个方法被执行。
So localhost:xxxx/HelloWorld/Index would cause the Index method of the HelloWorldController class to run. Notice
因此,localhost:xxxx/HelloWorld/Index 这个url将会引起 HelloWorldController 类中的 Index 方法被执行。
that you only had to browse to localhost:xxxx/HelloWorldand the Index method was called by default. This is
注意这个现象,你只在浏览器中请求了 localhost:xxxx/HelloWorld 而 Index 方法被默认调用。
because Index is the default method that will be called on a controller if a method name is not explicitly specified. The third part
这是因为当一个控制器的方法没有被明确指定时 index 是默认指定的方法。
of the URL segment ( id) is for route data. You'll see route data later on in this tutorial.
URL段的第三部分,id是一个路由数据。在本教程的后面部分你将会理解 route data。
Browse to http://localhost:xxxx/HelloWorld/Welcome. The Welcome method runs and returns the string "This is the
浏览 http://localhost:xxxx/HelloWorld/Welcome ,Welcome 方法将会被执行并返回字符串“This is the 。。。”。
Welcome action method...". For this URL, the controller is HelloWorld and Welcomeis the action method. You haven't used
对这个URL来说,控制器是 HelloWorld ,action 是 Welcome 方法。
the [Parameters] part of the URL yet.
到目前为止你还未使用URL段的 [Parameters] 部分。

Modify the code to pass some parameter information from the URL to the controller. For
修改代码,通过URL传递一些参数到控制器。
example, /HelloWorld/Welcome?name=Rick&numtimes=4. Change the Welcome method to include two parameters as shown in
例如,/HelloWorld/Welcome?name=Rick&numtimes=4 。像下面代码一样改变 Welcome 方法以包含两个参数。
the following code.
// GET: /HelloWorld/Welcome/
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int numTimes = )
{
return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}");
}
C# code
The preceding code:
之前的代码:
- Uses the C# optional-parameter feature to indicate that the numTimes parameter defaults to 1 if no value is passed for that
因为使用了C#可选参数特性,当 numTimes 这个参数没有指定值时他的值默认就是1 。
parameter.
- UsesHtmlEncoder.Default.Encode to protect the app from malicious input (namely JavaScript).
使用 HtmlEncoder.Default.Encode 方法可以使app避免恶意输入的攻击破坏。
- Uses Interpolated Strings.
使用字符串插值语法。
Run your app and browse to:
运行你的app并导航至下面的URL:
http://localhost:xxxx/HelloWorld/Welcome?name=Rick&numtimes=4
(Replace xxxx with your port number.) You can try different values for name and numtimes in the URL.
(用你自己的端口替换 xxxx)你可以尝试不容的参数值在URL中。
The MVC model binding system automatically maps the named parameters from the query string in the address bar to parameters
MVC 的模型绑定 会自动的映射URL中的命名参数的值到方法对应的参数上并赋值。
in your method. See Model Binding for more information.
可以查看模型绑定以获得更多信息。

In the image above, the URL segment (Parameters) is not used, the name and numTimes parameters are passed as query strings.
在上图中,URL段的参数部分未被使用,参数 name 和 numTimes 通过 查询字符串 的形式传递到后台。
The ? (question mark) in the above URL is a separator, and the query strings follow. The & character separates query strings.
? 是一个查询分隔符,后面跟的就是参数。符号& 分割了各个参数 。
Replace the Welcome method with the following code:
使用下面的代码替换 Welcome 方法:
public string Welcome(string name, int ID = )
{
return HtmlEncoder.Default.Encode($"Hello {name}, ID: {ID}");
}
C# code
Run the app and enter the following URL: http://localhost:xxx/HelloWorld/Welcome/3?name=Rick
运行app并输入地址:(上面的url)

This time the third URL segment matched the route parameter id. The Welcome method contains a parameter id that matched
这次URL段匹配了路由参数id。Welcome 方法包含一个id参数并被匹配上。
the URL template in the MapRoute method. The trailing ? (in id?) indicates the id parameter is optional.
URL模板在 MapRoute 方法中。尾部的 ? 表示id是一个可选参数。
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
C# code
In these examples the controller has been doing the "VC" portion of MVC - that is, the view and controller work. The controller is
在这些例子中我们已经使用了MVC中的V和C。
returning HTML directly. Generally you don't want controllers returning HTML directly, since that becomes very cumbersome to
控制器直接返回html。但是,通常我们不会用控制器直接返回HTML,因为这会使代码维护上非常的笨重。
code and maintain. Instead you typically use a separate Razor view template file to help generate the HTML response.
替代的,我们会使用一个Razor 视图模板辅助生成 HTML 响应。
You do that in the next tutorial.
你将会在后续的教程中这样做。
In Visual Studio, in non-debug mode (Ctrl+F5), you don't need to build the app after changing code. Just save the file, refresh your
在VS中,在非调试模式,当代码改变后你不需要重新编译代码,只需要保存文件,然后,
browser and you can see the changes.
刷新你的浏览器,就可以直接看到新的变更了。
蒙
2017-07-13 11:11 周四
006.Adding a controller to a ASP.NET Core MVC app with Visual Studio -- 【在asp.net core mvc 中添加一个控制器】的更多相关文章
- 【Asp.Net Core】一、Visual Studio 2015 和 .NET Core 安装
安装 Visual Studio 和 .NET Core 1.安装 Visual Studio Community 2015,选择 Community 下载并执行默认安装.Visual Studio ...
- Create an ASP.NET Core web app in Visual Studio Code
https://www.microsoft.com/net/core#windowscmd https://download.microsoft.com/download/B/9/F/B9F1AF57 ...
- 008.Adding a model to an ASP.NET Core MVC app --【在 asp.net core mvc 中添加一个model (模型)】
Adding a model to an ASP.NET Core MVC app在 asp.net core mvc 中添加一个model (模型)2017-3-30 8 分钟阅读时长 本文内容1. ...
- ASP.NET Core 中文文档 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 创建首个 Web API
原文:Building Your First Web API with ASP.NET Core MVC and Visual Studio 作者:Mike Wasson 和 Rick Anderso ...
- Working with Data » 使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程
原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web applica ...
- Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器
Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器 MVC概念 MVC的含义是 “模型-视图-控制器”.MVC是一个架构良好并且易于测试和易于维护的开发模式.基于MVC模式的应用程 ...
- 【翻译转载】【官方教程】Asp.Net MVC4入门指南(2):添加一个控制器
2. 添加一个控制器 · 原文地址:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-c ...
- 【转载】保哥 釐清 CLR、.NET、C#、Visual Studio、ASP.NET 各版本之間的關係
我常常不仅仅逛 博客园,还会去找国外,特别是台湾的技术部落格,发现好的文章,我便会收录,今天我转载或者全文复制,在Google 博客园,一位叫保哥, 釐清 CLR..NET.C#.Visual Stu ...
- Web Servers in Visual Studio for ASP.NET Web Projects
https://msdn.microsoft.com/en-us/library/58wxa9w5(v=vs.120).aspx When you develop web projects in Vi ...
随机推荐
- BAYESIAN STATISTICS AND CLINICAL TRIAL CONCLUSIONS: WHY THE OPTIMSE STUDY SHOULD BE CONSIDERED POSITIVE(转)
Statistical approaches to randomised controlled trial analysis The statistical approach used in the ...
- Spring与Mybatis整合
一 概述 1.整合的目的 将Mapper映射器的创建任务交给Spring容器. 二 具体实现 1.创建sqlSessionFactory: <bean id="sqlSessionFa ...
- python爬虫从入门到放弃(七)之 PyQuery库的使用
PyQuery库也是一个非常强大又灵活的网页解析库,如果你有前端开发经验的,都应该接触过jQuery,那么PyQuery就是你非常绝佳的选择,PyQuery 是 Python 仿照 jQuery 的严 ...
- golang实现dns域名解析(三):响应报文分析
前面说了构造请求发送报文,接下来我们好好研究下如何解析服务器端发回来的应答信息. 首先还是用前面的程序代码发一个请求,用抓包工具看看应答的内容有哪些: 截图的第一部分是返回信息的统计,表明这个返回的包 ...
- ASP.NET 开发者 开始学习ASP.NET Core 2吧
. NET Core 从2016年6月28日发布,过去了将近一年的时间,但是在工作中发现大家对.net core的接受程度并不高,这只是一个感觉,俗话说“没有调查就没有发言权”, 这两天通过微信小程 ...
- Sizzle 源码分析 (二)
在Sizzle函数中,如果能快速处理或者通过querySelector处理,那么就使用它处理.否则使用select函数处理 . select函数 select = Sizzle.select = fu ...
- PHP基础入门(三)---PHP函数基础
PHP基础入门(三)---函数 今天来给大家分享一下PHP的函数基础.有了前两章的了解,想必大家对PHP有了一定的基础了解.想回顾前两章的朋友可以点击"PHP基础入门(一)"&qu ...
- Discuz插件开发之全站论坛目录结构注释
基本上新版本的discuzX系列目录结构都差不多,刚好大神整理出来了,就拿来看吧. |-- /api uc.php UCenter通信文件 |-- /api/addon ...
- [转]html转码表
为什么要用转义字符串? HTML中<,>,&等有特殊含义(<,>,用于链接签,&用于转义),不能直接使用.这些符号是不显示在我们最终看到的网页里的,那如果我们希 ...
- 在windows下使用Qt5开发GTK3图形界面应用程序
首先,去MSYS2官网下载MSYS2环境并安装在C:/mysys64下,我安装的是64位的. 进入MSYS命令行执行: pacman -S mingw-w64-x86_64-gtk3 pacman - ...