第二篇 Asp.Net Core WebAPI 連接Sqlserver數據庫及WebAPI服務發布
前言 Core API可以在業務與數據的模式下提供了一項安全、可靠的數據接口服務方式,我們借助於Core API可以為移動端、物聯網終端、互聯網終端等設備提供在線數據訪問服務,本文重點介紹Core API項目創建、Sqlserver數據CRUD操作、服務發布(WinDows服務器和Linux服務器),側重入門實操,大俠繞步!
學習目標:
1)使用Vs2019創建Core API項目;
2)如何實現Core API連接Sqlserver數據庫,並且實現CRUD操作;
3)搭建Swagger,實現可視化的API頁面。
4)在Windows和Linux服務器發布Core API應用。
前期准備工具:
Vs2019 IDE環境、Sqlserver2008、Windows服務器、Linux服務器。
一、使用Vs2019創建WebAPI項目
新建一個項目名稱為WebApi的工程,Core版本選擇3.1,項目類型選擇“ASP.NET Core Web API”,如下圖所示
使用項目模板自動生成了一個未來5天天氣情況的Json字符串,運行后如下圖所示:
[{ "date": "2021-11-25T15:15:48.3451682+08:00", "temperatureC": 3, "temperatureF": 37, "summary": "Scorching" }, { "date": "2021-11-26T15:15:48.3481578+08:00", "temperatureC": 17, "temperatureF": 62, "summary": "Scorching" }, { "date": "2021-11-27T15:15:48.3481611+08:00", "temperatureC": -9, "temperatureF": 16, "summary": "Bracing" }, { "date": "2021-11-28T15:15:48.3481614+08:00", "temperatureC": 49, "temperatureF": 120, "summary": "Hot" }, { "date": "2021-11-29T15:15:48.3481615+08:00", "temperatureC": 35, "temperatureF": 94, "summary": "Warm" }]
項目中的文件和文件夾主要有:Controllers(控制器),appsettings.json(配置數據庫等連接參數),Program.cs(軟件啟動項設置),Startup.cs(注冊路由和服務)
二、建立SqlServer數據庫CRUD操作
2.1 配置Sqlserver參數,導入Core Nuget程序包
Core Web API和MVC配置類似,需要先導入NuGet包,appsettings.json文件中配置Sql數據庫連接參數,Startup.cs中配置連接服務。
三個NuGet包分別為:Microsoft.EntityFrameworkCore(5.0.12)、Microsoft.EntityFrameworkCore.SqlServer、Microsoft.EntityFrameworkCore.Tools、Microsoft.VisualStudio.Web.CodeGenerators.Design
右鍵點擊項目資源,選擇“管理NuGet程序包”
在appsetting.json文件中設置數據庫連接字符串
1 { 2 "Logging": { 3 "LogLevel": { 4 "Default": "Information", 5 "Microsoft": "Warning", 6 "Microsoft.Hosting.Lifetime": "Information" 7 } 8 }, 9 "AllowedHosts": "*", 10 "ConnectionStrings": { 11 "MVCSqlContext": "Server=localhost;Database=InfoUser;User ID=sa;Password=sa;" 12 } 13 }
在Startup.cs文件中配置連接服務,如下圖所示
1 // This method gets called by the runtime. Use this method to add services to the container. 2 public void ConfigureServices(IServiceCollection services) 3 { 4 services.AddControllersWithViews(); 5 //下面為加入的數據庫服務,注意MVCSqlContext修改為自己的文件名 6 services.AddDbContext<InfoUserContext>(options => 7 options.UseSqlServer(Configuration.GetConnectionString("MVCSqlContext"))); 8 9 10 11 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); 12 }
2.2 添加Model模型類、用於CRUDSqlserver數據業務的控制器
首先,在Sqlserver數據庫創建數據庫名為InfoUser的數據庫,建立一個UserData表,表結構如下:
在項目中添加一個“Models”文件夾,右鍵點擊Models添加類文件,類的名稱為UserData
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.ComponentModel.DataAnnotations; 6 using System.ComponentModel.DataAnnotations.Schema; 7 8 namespace MVC_SQL_Test.Models 9 { 10 public partial class UserData 11 { 12 [Key, Column(Order = 1)] 13 public int UserId { get; set; } 14 public string UserName { get; set; } 15 public string Password { get; set; } 16 } 17 }
手動添加一個API 控制器,右鍵點擊Models,依次選擇“添加”->"控制器"->“EF 控制器”
控制器自動生成后,點擊項目調試運行:https://localhost:44364/api/UserDatas/5,運行結果如下:
注意:在API項目中也可以同時創建MVC 控制器和Views頁面,可參考第一篇。
三、創建Swagger可視化(RESTFull)服務
第一步:需要導入Swagger NuGet包,右鍵選中項目依次點擊“NuGet包管理器”->輸入“Swashbuckle.AspNetCore”
第二步:在Startup.cs文件中注冊Swagger服務,代碼如下圖所示:
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.AspNetCore.Hosting; 3 using Microsoft.AspNetCore.HttpsPolicy; 4 using Microsoft.AspNetCore.Mvc; 5 using Microsoft.Extensions.Configuration; 6 using Microsoft.Extensions.DependencyInjection; 7 using Microsoft.Extensions.Hosting; 8 using Microsoft.Extensions.Logging; 9 using Microsoft.OpenApi.Models; 10 using System; 11 using System.Collections.Generic; 12 using System.Linq; 13 using System.Threading.Tasks; 14 using Microsoft.EntityFrameworkCore; 15 using WebApi.Data; 16 17 namespace WebApi 18 { 19 public class Startup 20 { 21 public Startup(IConfiguration configuration) 22 { 23 Configuration = configuration; 24 } 25 26 public IConfiguration Configuration { get; } 27 28 // This method gets called by the runtime. Use this method to add services to the container. 29 public void ConfigureServices(IServiceCollection services) 30 { 31 32 services.AddControllers(); 33 services.AddSwaggerGen(c => 34 { 35 c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi", Version = "v1" }); 36 }); 37 38 services.AddDbContext<WebApiContext>(options => 39 options.UseSqlServer(Configuration.GetConnectionString("WebApiContext"))); 40 } 41 42 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 43 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 44 { 45 if (env.IsDevelopment()) 46 { 47 app.UseDeveloperExceptionPage(); 48 app.UseSwagger(); 49 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi v1")); 50 } 51 52 app.UseHttpsRedirection(); 53 54 app.UseRouting(); 55 56 app.UseAuthorization(); 57 58 app.UseEndpoints(endpoints => 59 { 60 endpoints.MapControllers(); 61 }); 62 } 63 } 64 }
最終運行效果如下圖所示: