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 分钟阅读时长 

By Rick Anderson

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 中,输入以下代码:

 1 using Microsoft.AspNetCore.Mvc;
 2 
 3 using System.Text.Encodings.Web;
 4 
 5  
 6 
 7 namespace MvcMovie.Controllers
 8 
 9 {
10 
11     public class HelloWorldController : Controller
12 
13     {
14 
15         //
16 
17         // GET: /HelloWorld/
18 
19  
20 
21         public string Index()
22 
23         {
24 
25             return "This is my default action...";
26 
27         }
28 
29  
30 
31         //
32 
33         // GET: /HelloWorld/Welcome/
34 
35  
36 
37         public string Welcome()
38 
39         {
40 
41             return "This is the Welcome action method...";
42 
43         }
44 
45     }
46 
47 }
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  文件中,设置路由规则。

 1 app.UseMvc(routes =>
 2 
 3 {
 4 
 5     routes.MapRoute(
 6 
 7         name: "default",
 8 
 9         template: "{controller=Home}/{action=Index}/{id?}");
10 
11 });
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.

 1 // GET: /HelloWorld/Welcome/
 2 
 3 // Requires using System.Text.Encodings.Web;
 4 
 5 public string Welcome(string name, int numTimes = 1)
 6 
 7 {
 8 
 9     return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}");
10 
11 }
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避免恶意输入的攻击破坏。

使用字符串插值语法。

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 方法:

1 public string Welcome(string name, int ID = 1)
2 
3 {
4 
5     return HtmlEncoder.Default.Encode($"Hello {name}, ID: {ID}");
6 
7 }
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是一个可选参数。

 1 app.UseMvc(routes =>
 2 
 3 {
 4 
 5     routes.MapRoute(
 6 
 7         name: "default",
 8 
 9         template: "{controller=Home}/{action=Index}/{id?}");
10 
11 });
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 周四

 

转载于:https://www.cnblogs.com/Meng-NET/p/7159448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值