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-Control ...
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 中,輸入以下代碼:
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避免惡意輸入的攻擊破壞。
- 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 方法:
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 周四