使用 ASP.NET Core MVC 創建 Web API
使用 ASP.NET Core MVC 創建 Web API(一)
六、添加數據庫上下文
數據庫上下文是使用Entity Framework Core功能的主類。 此類由 Microsoft.EntityFrameworkCore.DbContext
類派生而來。
1) 在Visual Studio 2017的“解決方案資源管理器”中,右鍵單擊“Models”文件夾,然后選擇“添加” > “類”。 將類命名為 BookContext,然后單擊“添加”。
2) 在Visual Studio 2017的“解決方案資源管理器”中使用鼠標雙擊打開BookContext.cs文件,並輸入以下代碼:
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BookApi.Models { public class BookContext: DbContext { public BookContext(DbContextOptions<BookContext> options) : base(options) { } public DbSet<Book> Book { get; set; } } }
七、注冊數據庫上下文
在 ASP.NET Core 中,服務(如數據庫上下文)必須向依賴關系注入 (DI) 容器進行注冊。該容器向控制器提供服務。
在Visual Studio 2017中的“解決方案資源管理器”中找到 Startup.cs文件,雙擊打開之后,添加將數據庫上下文注入到DI容器中的代碼。代碼如下。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookApi.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace BookApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BookContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BookContext"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // 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.UseMvc(); } } }
八、添加數據庫連接
在Visual Studio 2017中的“解決方案資源管理器”中找到 appsettings.json文件,雙擊打開,然后添加數據庫連接字符串。文件中的配置代碼如下。
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "BookContext": "Server=.\\sqlexpress;Database=CustomDB;Trusted_Connection=True;MultipleActiveResultSets=true" }, "AllowedHosts": "*" }
九、 添加控制器
1) 在Visual Studio 2017中的“解決方案資源管理器”中右鍵單擊 Controllers 文件夾。在彈出菜單中選擇 添加 > 新建項。如下圖。
2) 在“添加新項-BookApi”對話框中,選擇“Web”—>“API 控制器類”模板,並在“名稱”輸入框中輸入 BookController,然后選擇“添加”按鈕。如下圖。
3) 在Visual Studio 2017中打開BookController.cs文件中添加以下代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookApi.Models; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BookApi.Controllers { [Route("api/[controller]")] [ApiController] public class BookController : Controller { private readonly BookContext _context; public BookController(BookContext context) { _context = context; if (_context.Book.Count() == 0) { context.Book.AddRange( new Book { Name = "Python編程 從入門到實踐", ReleaseDate = DateTime.Parse("2018-1-12"), Author = "埃里克·馬瑟斯", Price = 75.99M, Publishing = "機械出版社" }, new Book { Name = "Java編程的邏輯", ReleaseDate = DateTime.Parse("2018-1-13"), Author = "馬俊昌", Price = 48.50M, Publishing = "機械出版社" }, new Book { Name = "統計思維:大數據時代瞬間洞察因果的關鍵技能", ReleaseDate = DateTime.Parse("2017-12-23"), Author = "西內啟", Price = 39.00M, Publishing = "清華出版社" }, new Book { Name = "微信營銷", ReleaseDate = DateTime.Parse("2018-01-05"), Author = "徐林海", Price = 36.90M, Publishing = "清華出版社" }, new Book { Name = "Java 8實戰", ReleaseDate = DateTime.Parse("2016-04-05"), Author = "厄馬", Price = 65.60M, Publishing = "科技出版社" } ); _context.SaveChanges(); } } } }
對於上面的代碼的說明:
1) 定義了沒有方法的 API 控制器類。
2) 使用 [ApiController]
屬性修飾類。 此屬性指示控制器響應 Web API 請求。
從 ASP.NET Core 2.1 開始,使用 [ApiController]
特性修飾控制器類時,將啟用操作參數綁定源推理。復雜類型參數通過請求正文自動綁定。 因此,不會使用 [FromBody] 特性對前面操作中的 Book
參數進行顯示批注。在 ASP.NET Core 2.2 或更高版本中,可將 [ApiController] 特性應用於程序集。 以這種方式進行注釋,會將 web API 行為應用到程序集中的所有控制器。 請注意,無法針對單個控制器執行選擇退出操作。
[ApiController] 特性通常結合 Controller 來為控制器啟用特定於 REST 行為。 通過 Controllere 可使用NotFound 和 File 等方法。
另一種方法是創建使用 [ApiController] 特性進行批注的自定義基本控制器類:
[ApiController] public class MyBaseController { }
3) 使用 DI 將數據庫上下文 (BookContext
) 注入到控制器中。 數據庫上下文將在控制器中的每個 CRUD 方法中使用。
4) 如果數據庫為空,則將幾條書籍信息數據添加到數據庫。 此代碼位於構造函數中,因此在每次出現新 HTTP 請求時運行。 如果刪除所有項,則構造函數會在下次調用 API 方法時再次創建。 因此刪除可能看上去不起作用,不過實際上確實有效。