開始使用 ASP.NET CoreGetting Started with ASP.NET Core

Visual Studio for Mac 可讓您輕鬆地開發應用程式的服務,並支援最新的 ASP.NET Core Web 開發平臺。Visual Studio for Mac makes it easy to develop your app's service with its support for the latest ASP.NET Core Web development platform. ASP.NET Core 在 .NET Core 上執行,而 .NET Core 是 .NET Framework 和執行階段的最新演進。ASP.NET Core runs on .NET Core, the latest evolution of the .NET Framework and runtime. 它已針對快速效能進行調整,並針對小型安裝大小和重新發想在 Linux 和 macOS 上執行,以及 Windows 上執行。It's been tuned for fast performance, factored for small install sizes, and reimagined to run on Linux and macOS, as well as Windows.

安裝 .NET CoreInstalling .NET Core

當您安裝 Visual Studio for Mac 時,會自動安裝 .NET Core 3.1。.NET Core 3.1 is automatically installed when you install Visual Studio for Mac. 如需 Visual Studio for Mac 中支援之 .NET Core 版本的詳細資訊,請參閱 .Net Core 支援For more information about versions of .NET Core supported in Visual Studio for Mac, see .NET Core Support.

在 Visual Studio for Mac 中建立 ASP.NET Core 應用程式Creating an ASP.NET Core app in Visual Studio for Mac

開啟 Visual Studio for Mac。Open Visual Studio for Mac. 在開始畫面選取 [新增專案]On the Start Screen, select New Project...

New Project Dialog

這會顯示 [新增專案] 對話方塊,可讓您選取範本來建立應用程式。This will display the New Project dialog, allowing you to select a template to create your application.

有許多專案可為您提供預先建立的範本,以開始建置 ASP.NET Core 應用程式。There are a number of projects that will provide you with a pre-built template to start building your ASP.NET Core Application. 這些警告是:These are:

  • .NET Core > 空白.NET Core > Empty
  • .NET Core > API.NET Core > API
  • .NET Core > Web 應用程式.NET Core > Web Application
  • .NET Core > Web 應用程式 (模型-檢視-控制器).NET Core > Web Application (Model-View-Controller)
  • .NET Core > :::no-loc(Blazor)::: Server 應用程式.NET Core > :::no-loc(Blazor)::: Server App
  • .NET Core > :::no-loc(Blazor WebAssembly)::: 應用程式.NET Core > :::no-loc(Blazor WebAssembly)::: App

ASP.NET 專案選項

選取 [ASP.NET Core 空白 Web 應用程式],然後按 [下一步]。Select the ASP.NET Core Empty Web Application and press Next. 提供專案名稱,然後按 [建立]。Give the Project a Name and press Create. 這會建立新的 ASP.NET Core 應用程式。This creates a new ASP.NET Core app. 在方案視窗的左窗格中,展開第二個箭號,然後選取 [ Startup.cs ]。In the solution window's left pane, expand the second arrow and then select Startup.cs. 它看起來應該如下圖所示:It should look similar to the image below:

新的 ASP.NET Core 空白專案檢視

ASP.NET Core 空白範本會建立具有兩個預設檔案的 web 應用程式: Program.csStartup.cs ,如下所述。The ASP.NET Core Empty template creates a web application with two default files: Program.cs and Startup.cs , which are explained below. 它也會建立相依性資料夾,其中包含專案的 NuGet 套件相依性,例如 ASP.NET Core、.NET Core framework 和建立專案的 MSBuild 目標:It also creates a Dependencies folder, which contains your project's NuGet package dependencies such as ASP.NET Core, the .NET Core framework, and the MSBuild targets that build the project:

顯示相依性的解決方案視窗

Program.csProgram.cs

在專案中開啟並檢查 Program.cs 檔案。Open and inspect the Program.cs file in your project. 請注意,Main 方法中會發生幾件事 - 對應用程式的輸入:Notice that several things are happening in the Main method – the entry into your app:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

ASP.NET Core 的應用程式會透過的實例設定和啟動主機,以在其主要方法中建立 web 伺服器 WebHostBuilderAn ASP.NET Core app creates a web server in its main method by configuring and launching a host via an instance of WebHostBuilder. 這個建立器提供了一些方法來允許設定主機。This builder provides methods to allow the host to be configured. 在範本應用程式中,會使用下列設定:In the template app, the following configurations are used:

  • .UseStartup<Startup>():指定啟動類別。.UseStartup<Startup>(): Specifies the Startup class.

不過,您也可以新增其他組態,例如:However, you can also add additional configurations, such as:

  • UseKestrel:指定應用程式將使用的 Kestrel 伺服器UseKestrel: Specifies the Kestrel server will be used by the app
  • UseContentRoot(Directory.GetCurrentDirectory()):當應用程式從 Web 專案的根資料夾啟動時,使用這個資料夾作為應用程式的內容根目錄UseContentRoot(Directory.GetCurrentDirectory()): Uses the web project's root folder as the app's content root when the app is started from this folder
  • .UseIISIntegration():指定應用程式應該使用 IIS。.UseIISIntegration(): Specifies that the app should work with IIS. 若要搭配使用 IIS 與 ASP.NET Core,必須同時指定 UseKestrelUseIISIntegrationTo use IIS with ASP.NET Core both UseKestrel and UseIISIntegration need to be specified.

Startup.csStartup.cs

應用程式的啟動類別是在 CreateWebHostBuilderUseStartup() 方法中指定。The Startup class for your app is specified in the UseStartup() method on the CreateWebHostBuilder. 在這個類別中,您將指定要求處理管線,並在其中設定任何服務。It is in this class that you will specify the request handling pipeline, and where you configure any services.

在專案中開啟並檢查 Startup.cs 檔案:Open and inspect the Startup.cs file in your project:

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

這個啟動類別必須一律遵守下列規則:This Startup class must always adhere to the following rules:

  • 必須一律為公用It must always be public
  • 必須包含兩個公用方法:ConfigureServicesConfigureIt must contain the two public methods: ConfigureServices and Configure

ConfigureServices 方法會定義您的應用程式將使用的服務。The ConfigureServices method defines the services that will be used by your app.

Configure 可讓您使用中介軟體撰寫要求管線。The Configure allows you to compose your request pipeline using Middleware. 這些是 ASP.NET 應用程式管線中用來處理要求和回應的元件。These are components used within an ASP.NET application pipeline to handle requests and responses. HTTP 管線包含許多要求委派,這些委派將依順序呼叫。The HTTP pipeline consists of a number of request delegates, called in sequence. 每個委派可以選擇處理要求本身,或將它傳遞至下一個委派。Each delegate can choose to either handle the request itself, or pass it to the next delegate.

您可以在 IApplicationBuilder 上使用 RunMapUse 方法來設定委派,但 Run 方法永遠不會呼叫下一個委派,因此應該一律在管線結尾處使用。You can configure delegates by using the Run,Map, and Use methods on IApplicationBuilder, but the Run method will never call a next delegate and should always be used at the end of your pipeline.

預先建立範本的 Configure 方法是為了執行一些作業而建立的。The Configure method of the pre-built template is built to do a few things. 首先,它會設定例外狀況處理頁面以供開發期間使用。First, it configures an exception handling page for use during development. 然後,它會以簡單的 "Hello World" 傳送回應給要求網頁。Then, it sends a response to the requesting web page with a simple "Hello World".

現在,無需新增任何其他程式碼,即可執行這個簡單的 Hello, World 專案。This simple Hello, World project can run now without any additional code being added. 若要執行應用程式,您可以使用 [播放] 按鈕的下拉式清單選取您想要用來執行應用程式的瀏覽器,或直接按下 [播放] (三角形) 按鈕,以使用您的預設瀏覽器:To run the app, you can either select which browser you want to run app the app in using the dropdown right of the Play button, or simply hit the Play (triangular) button to use your default browser:

瀏覽器執行

Visual Studio for Mac 會使用隨機的連接埠來啟動您的 Web 專案。Visual Studio for Mac uses a random port to launch your web project. 若要瞭解這是什麼埠,請開啟 [應用程式輸出],它會列在 [ > 其他視窗 ] 功能表的 [View] 之下。To find out what port this is, open the Application Output, which is listed under the View > Other Windows menu. 您應該尋找的輸出類似如下:You should find output similar to that shown below:

顯示接聽連接埠的應用程式輸出

專案一經執行,您的預設網頁瀏覽器就應該啟動,並連線到應用程式輸出列出的 URL。Once the project is running, your default web browser should launch and connect to the URL listed in the Application Output. 或者,您可以開啟選擇的任何瀏覽器,輸入 http://localhost:5000/,將 5000 取代為應用程式輸出中的 Visual Studio 輸出連接埠。Alternatively, you can open any browser of your choice, and enter http://localhost:5000/, replacing the 5000 with the port that Visual Studio output in the Application Output. 您應該會看到文字 Hello World!You should see the text Hello World!:

顯示文字的瀏覽器

新增控制器Adding a Controller

ASP.NET Core 應用程式使用「模型-檢視-控制器 (MVC)」設計模式,為應用程式的每個部分提供責任的邏輯分隔。ASP.NET Core Apps use the Model-View-Controller (MVC) design pattern to provide a logical separation of responsibilities for each part of the app. MVC 設計模式包含下列概念:The MVC design pattern consists of the following concepts:

  • 模型 :代表應用程式資料的類別。Model : A class that represents the data of the app.
  • 檢視 :顯示應用程式的使用者介面 (這通常是模型資料)。View : Displays the app's user interface (which is often the model data).
  • 控制器 :用來處理瀏覽器要求、回應使用者輸入和互動的類別。Controller : A class which handles browser requests, responds to user input and interaction.

如需有關使用 MVC 的詳細資訊,請參閱 ASP.NET CORE mvc 指南的總覽。For more information on using MVC, see the Overview of ASP.NET Core MVC guide.

若要新增控制器,請執行下列作業:To add a controller, do the following:

  1. 以滑鼠右鍵按一下專案名稱,然後選取 [新增] > [新增檔案]。Right-click on the Project name and select Add > New Files. 選取 [一般] > [空白類別],然後輸入控制器名稱:Select General > Empty Class , and enter a controller name:

    [新增檔案] 對話方塊

  2. 將下列程式碼新增至新控制器:Add the following code to the new controller:

    using System;
    using Microsoft.AspNetCore.Mvc;
    using System.Text.Encodings.Web;
    
    namespace Hello_ASP
    {
        public class HelloWorldController : Controller
        {
            //
            // GET: /HelloWorld/
    
            public string Index()
            {
                return "This is my default action...";
            }
    
        }
    }
    
  3. 以滑鼠右鍵按一下 [相依性] 資料夾,然後選取 [新增套件...],將 Microsoft.AspNetCore.Mvc 相依性新增至專案。Add the Microsoft.AspNetCore.Mvc dependency to the project by right-clicking the Dependency folder, and selecting Add Package....

  4. 使用搜尋方塊來瀏覽 NuGet 程式庫以找出 Microsoft.AspNetCore.Mvc,然後選取 [新增套件]。Use the Search box to browse the NuGet library for Microsoft.AspNetCore.Mvc, and select Add Package. 這可能需要幾分鐘的時間來完成安裝,而且系統可能會提示您接受所需相依性的各種授權:This may take a few minutes to install and you may be prompted to accept various licenses for the required dependencies:

    新增 Nuget

  5. 在啟動類別中,移除 app.Run Lambda,並將 MVC 用來判斷所應叫用程式碼的 URL 路由邏輯設為下列內容:In the Startup class, remove the app.Run lambda and set the URL routing logic used by MVC to determine which code it should invoke to the following:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
        name: "default",
        template: "{controller=HelloWorld}/{action=Index}/{id?}");
    });
    

    請務必移除 app.Run Lambda,因為這會覆寫路由邏輯。Make sure to remove the app.Run lambda, as this will override the routing logic.

    MVC 會使用下列格式來判斷要執行的程式碼:MVC uses the following format, to determine which code to run:

    /[Controller]/[ActionName]/[Parameters]

    當您新增上述的程式碼片段時,即是告訴應用程式預設為 HelloWorld 控制器及 Index 動作方法。When you add the code snippet above, you are telling the app to default to the HelloWorld Controller, and the Index action method.

  6. services.AddMvc(); 呼叫新增至 ConfigureServices 方法,如下所示:Add the services.AddMvc(); call to the ConfigureServices method, as illustrated below:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
    

    您也可以將 URL 中的參數資訊傳遞到控制器。You can also pass parameter information from the URL to the controller.

  7. 將另一個方法新增至 HelloWorldController,如下所示:Add another method to your HelloWorldController, as illustrated below:

    public string Xamarin(string name)
    {
        return HtmlEncoder.Default.Encode($"Hello {name}, welcome to Visual Studio for Mac");
    }
    
  8. 如果您立即執行應用程式,它應該會自動開啟您的瀏覽器:If you run the app now, it should automatically open your browser:

    在瀏覽器中執行應用程式

  9. 嘗試瀏覽至 http://localhost:xxxx/HelloWorld/Xamarin?name=Amy(將 xxxx 取代為正確的連接埠),您應該會看到下列內容:Try to browse to http://localhost:xxxx/HelloWorld/Xamarin?name=Amy (replacing xxxx with the correct port), you should see the following:

    使用引數在瀏覽器中執行應用程式

疑難排解Troubleshooting

如果您需要在 macOS 10.12 (內部) 和更高版本上手動安裝 .NET Core,請執行下列動作:If you need to install .NET Core manually on macOS 10.12 (Sierra) and higher, do the following:

  1. 在開始安裝 .NET Core 之前,請確定所有作業系統更新已更新為最新穩定版本。Before you start installing .NET Core, ensure that you have updated all OS updates to the latest stable version. 若要檢查此項,請移至應用程式市集應用程式,然後選取 [更新] 索引標籤。You can check this by going to the App Store application, and selecting the Updates tab.

  2. 遵循 .NET Core 網站上所列出的步驟。Follow the steps listed on the .NET Core site.

請務必順利完成所有步驟,以確保成功安裝 .NET Core。Make sure to complete all steps successfully to ensure that .NET Core is installed successfully.

總結Summary

本指南提供了 ASP.NET Core 的簡介。This guide gave an introduction to ASP.NET Core. 當中描述其概念和使用時機,並提供了如何在 Visual Studio for Mac 中使用它的資訊。It describes what it is, when to use it, and provided information on using it in Visual Studio for Mac. 如需下一個步驟的詳細資訊,請參閱下列指南:For more information on the next steps from here, see the following guides: