.NETCORE WEBAPI 搭建


最近一直有小項目用到 WebApi現在整理一下思路,寫一份說明出來,讓后來人不走彎路.......

1. 第一步 新建項目

  • 打開VS2019,選擇新建項目,選擇ASP.NET Core Web 應用程式

  • 設置好專案名稱

  • 創建API 應用程式

 

2.第二步 Nuget 所需包准備

  • IdentityServer4

  • IdentityServer4.AccessTokenValidation

  • WebApiClient.JIT

    關於這三個包這里不做過多敘述,這里先負責搭建運行,如有必要后期單獨說明

3.第三步 identityserver4環境配置

首先建一個 IdentityConfig類

  public class IdentityConfig
  {
      /// <summary>
      ///   ApiResource
      /// </summary>
      /// <returns></returns>
      public static IEnumerable<ApiResource> GetResource =>
            new List<ApiResource>() {
              new ApiResource("api1","My API")
            };
      /// <summary>
      /// Client
      /// </summary>
      /// <returns></returns>
      public static IEnumerable<Client> GetClients =>
          new List<Client>
          {
              new Client
              {
                  ClientId="client",//這里設置賬號
                  AllowedGrantTypes =GrantTypes.ClientCredentials,
                  ClientSecrets={
                  new Secret("aju".Sha256())//這里設置加密
                  },
                  AllowedScopes={ "api1"}
              }
          };
  }

按提示引用 using IdentityServer4.Models;

在Startup文件中注冊 identityserver4

ConfigureServices中

 //依賴注入系統中注冊IdentityServer
          services.AddIdentityServer()
              .AddDeveloperSigningCredential()//擴展在每次啟動時,為令牌簽名創建了一個臨時密鑰。在生成環境需要一個持久化的密鑰
              .AddInMemoryApiResources(IdentityConfig.GetResource)//Api 資源
              .AddInMemoryClients(IdentityConfig.GetClients);//Api的客戶端

          services.AddControllers();

          services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>
          {
              options.Authority = "https://localhost:61399";//這里填寫WEBAPI地址
              options.RequireHttpsMetadata = false;
              options.Audience = "api1";
          });

Configure中新增

   app.UseIdentityServer();//使用服務 中間件被添加到HTTP管道中

app.UseAuthentication();//將身份認證服務添加到DI比配置Bearer為默認||將身份認證服務添加到管道中,以便對主機的每次調用都將自動執行身份驗證||添加授權中間件,以確保匿名客戶端無法訪問我們的API資源

4.新建webapi控制器

  • 項目建好后新建空的WEBAPI控制器

  • 在新建的HomeController.cs中 引用 Microsoft.AspNetCore.Authorization 包

在控制器上添加 [Authorze]

 

  • 開始寫相關業務邏輯方法 Add() 注意:控制器上的路由和方法上的路由為訪問地址

5.Postman測試

  • 獲取token

    采用post方式,地址為connect/token

    參數 grant_type 采用 client_credentials

    client_id 在第三步配置IdentityServer4環境中設置 client

    client_secret 在第三步配置IdentityServer4環境中設置 aju

  • 執行Add方法

    將上一步獲取的token放入 postman Authorization 的 Access Token 中

    訪問地址 http://localhost:63199/api/Home/Add

    只要 返回狀態為 200 OK時即成功

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM