一、步驟
從“檔案”選單中選擇“新建”>“專案” ,
選擇“ASP.NET Core Web 應用程式”模板,再單擊“下一步” ,

將專案命名為 NetCoreWebApi,然后單擊“創建” ,

選擇“.NET Core”和“ASP.NET Core 2.2” , 選擇“API”模板,然后單擊“創建” ,

創建完成后,專案結構如下:

二、專案解讀
Properties——launchSettings.json
啟動組態檔,一個ASP.NET Core應用保存特有的配置標準,用于應用的啟動準備作業,包括環境變數,開發埠等,
1 { 2 "$schema": "http://json.schemastore.org/launchsettings.json", 3 "iisSettings": { //選擇以IIS Express啟動 4 "windowsAuthentication": false, //是否啟用windows身份驗證 5 "anonymousAuthentication": true, //是否啟用匿名身份驗證 6 "iisExpress": { 7 "applicationUrl": "http://localhost:60953", //IIS Express隨機埠 8 "sslPort": 0 9 } 10 }, 11 "profiles": { 12 "IIS Express": { 13 "commandName": "IISExpress", 14 "launchBrowser": true, //是否在瀏覽器中啟動 15 "launchUrl": "api/values", //在瀏覽器中啟動的相對URL 16 "environmentVariables": { //將環境變數設定為鍵/值對 17 "ASPNETCORE_ENVIRONMENT": "Development" 18 } 19 }, 20 "NetCoreWebApi": { 21 "commandName": "Project", 22 "launchBrowser": true, 23 "launchUrl": "api/values", 24 "applicationUrl": "http://localhost:5000", 25 "environmentVariables": { 26 "ASPNETCORE_ENVIRONMENT": "Development" 27 } 28 } 29 } 30 }
appsetting.json
appsetting.json是應用程式組態檔,類似于ASP.NET MVC應用程式中的Web.config組態檔,
例如:連接字串,等等....
1 { 2 "Logging":{ 3 "LogLevel":{ 4 "Default":"Warning" 5 } 6 }, 7 "AllowedHosts":"*", 8 "ConnectionStrings":{ 9 "SqlServer":"Data Source=.;Initial Catalog=NetCoreWebApi;User Id=sa;Password=123;" 10 } 11 }
Program.cs
Program.cs檔案是應用的入口, 啟動后通過UseStartup<Startup>()指定下文的Startup啟動檔案進行啟動,
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 CreateWebHostBuilder(args).Build().Run(); 6 } 7 8 public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 9 WebHost.CreateDefaultBuilder(args)//創建WebHostBuilder, 10 .UseStartup<Startup>();//指定啟動類,用于依賴注入和中間件注冊, 11 }
Startup.cs
該檔案是默認檔案,不可隨意洗掉,在此檔案中可以以包含服務配置、定義請求處理管道的重要操作,
ConfigureServices 方法用于將服務注入到 IServiceCollection 服務容器中,
Configure方法用于應用回應 HTTP 請求,將中間件注冊到 ApplicationBuilder中來配置請求管道,
1 public class Startup 2 { 3 public Startup(IConfiguration configuration) 4 { 5 Configuration = configuration; 6 } 7 8 public IConfiguration Configuration { get; } 9 10 //負責注入服務 11 public void ConfigureServices(IServiceCollection services) 12 { 13 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 14 } 15 16 // 回應 HTTP 請求的方式,可將中間件注冊到IApplicationBuilder 實體來配置請求管道, 17 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 18 { 19 if (env.IsDevelopment()) 20 { 21 app.UseDeveloperExceptionPage(); 22 } 23 24 app.UseMvc(); 25 } 26 }
三、測驗
此時專案已經完成,按 Ctrl+F5 運行之后,就能看到
?
這是一個最基礎的.NET Core API 環境,離我們想要的API框架還很遠,但是其實已經成功一半了,因為好的開始是成功的一半!??
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/91636.html
標籤:.NET Core
