使用 ASP.NET Core MVC 建立 Web API(二)

使用 ASP.NET Core MVC 建立 Web APIhtml

使用 ASP.NET Core MVC 建立 Web API(一)web

 

 

6、添加數據庫上下文

      數據庫上下文是使用Entity Framework Core功能的主類。 此類由 Microsoft.EntityFrameworkCore.DbContext 類派生而來。sql

    1) 在Visual Studio 2017的「解決方案資源管理器」中,右鍵單擊「Models」文件夾,而後選擇「添加」 > 「類」。 將類命名爲 BookContext,而後單擊「添加」。數據庫

     2) 在Visual Studio 2017的「解決方案資源管理器」中使用鼠標雙擊打開BookContext.cs文件,並輸入如下代碼:express

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; }     

    }
}

 

7、註冊數據庫上下文

     在 ASP.NET Core 中,服務(如數據庫上下文)必須向依賴關係注入 (DI) 容器進行註冊。該容器向控制器提供服務。編程

     在Visual Studio 2017中的「解決方案資源管理器」中找到 Startup.cs文件,雙擊打開以後,添加將數據庫上下文注入到DI容器中的代碼。代碼以下。json

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();
        }
    }
}

 

8、添加數據庫鏈接

      在Visual Studio 2017中的「解決方案資源管理器」中找到 appsettings.json文件,雙擊打開,而後添加數據庫鏈接字符串。文件中的配置代碼以下。api

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "BookContext": "Server=.\\sqlexpress;Database=CustomDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AllowedHosts": "*"
}

 

9、 添加控制器

    1) 在Visual Studio 2017中的「解決方案資源管理器」中右鍵單擊 Controllers 文件夾。在彈出菜單中選擇 添加 > 新建項。以下圖。微信

 

     2) 在「添加新項-BookApi」對話框中,選擇「Web」—>「API 控制器類」模板,並在「名稱」輸入框中輸入 BookController,而後選擇「添加」按鈕。以下圖。app

 

     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 方法時再次建立。 所以刪除可能看上去不起做用,不過實際上確實有效。

相關文章
相關標籤/搜索