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 ...
随机推荐
- axis2 和 xfire 接口调用问题排查
背景: 1个运营商厂家开发人员离职,我们为了上线对接接口,迁就对方客户端调用.对方客户端框架用的是xfire.调用方式基本为: Service serviceModel = new ObjectS ...
- 详解Centos默认磁盘分区
对于有经验的Linux系统管理员,在安装系统之前都会对系统的分区进行规划:针对这一需求,下面就通过默认的Centos分区与大家分享一些关于Linux系统的知识.Linux系统的磁盘命名规范:硬盘类型标 ...
- C#基础篇--面向对象(类与对象)
1.类是什么? 类就相当于模板,就是把同一类的事物的共同特征进行的抽象. 类的创建和说明: 类是先根据一些具体的对象(实体的东西)来抽象出来的共同的特性,然后用代码来表示. 在类中,用数据表示事物的 ...
- 一天搞定CSS:支持IE的Layout布局--16
1.BFC和Layout区别: BFC和Layout的作用是一样的,只是对浏览器的支持不同而已. BFC- -标准浏览器所具有的 Layout- -IE浏览器所具有的 BFC详解地址:http://b ...
- 【小练习02】CSS--网易产品
要求用css和HTML实现下图效果: 代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8& ...
- javaSE_07Java中类和对象-封装特性
一.谈谈什么是面向对象的思维 理解面向对象,重点是要思考以下的问题 面向过程 vs 面向对象 Ø 谈谈什么是面向过程的编程思想? Ø 为什么有面向过程还要有面向对象? Ø 谈谈什么是面向对象的编程思想 ...
- css块级元素居中
<!DOCTYPE html> <html> <head> <title>index</title> </head> <b ...
- 使用React改版网站后的一些感想
文章转载:http://www.jianshu.com/p/8f74cfb146f7 网站是毕业设计的作品,开发这个网站的目的主要用于记录一些笔记,以及聚合一些资讯信息,也算自己在网络世界中的一块静地 ...
- Python初探
Q:DBA是运维数据库,为什么还要懂开发? A: 维护:维护的机器太多了,很多重复的操作,需要开发出工具来实现 监控:所有机器的运行情况和健康状况都需要了解,全盘掌握cup.内存.磁盘.网络流量.数据 ...
- java基础(十五章)
一.字符串类String 1.String是一个类,位于java.lang包中 2.创建一个字符串对象的2种方式: String 变量名="值"; String 对象名=new S ...