《Asp.Net Core3 + Vue3入坑教程》-Net Core專案搭建與Swagger配置步驟

Iannnnnnnnnnnnn發表於2021-02-26

簡介

《Asp.Net Core3 + Vue3入坑教程》 此教程僅適合新手入門或者前後端分離嘗試者。可以根據圖文一步一步進操作編碼也可以選擇直接檢視原始碼。每一篇文章都有對應的原始碼

教程後期會將 .Net Core 3升級成 .Net Core 5

目錄

《Asp.Net Core3 + Vue3入坑教程》系列教程目錄

Asp.Net Core後端專案

  1. 後端專案搭建與Swagger配置步驟
  2. (暫未發表敬請期待...)CORS跨域問題處理
  3. (暫未發表敬請期待...)AutoMapper & Restful API
  4. (暫未發表敬請期待...)EF Core & Postgresql
  5. (暫未發表敬請期待...).Net Core 3升級成 .Net Core 5
  6. (暫未發表敬請期待...)JWT

Vue3 前端專案

暫未發表敬請期待...

本文簡介

本文為《Asp.Net Core3 + Vue3入坑教程》系列教程的後端開篇,主要介紹 Asp.Net Core Web後端專案的搭建流程與Swagger配置。

Simple專案搭建流程與Swagger配置步驟

新建專案



引入Swagger Nuget包


配置Starup.cs

程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Simple_Asp.Net_Core.ServiceProvider;

namespace Simple_Asp.Net_Core
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSwagger();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
                });
            }

            app.UseRouting();
            app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
        }
    }
}

配置XML 文件檔案

目的是讓專案的註釋能夠展示在swagger頁面上 。XML 文件檔案的路徑需要與下一步Swagger擴充套件類的檔案路徑一致

var xmlPath = Path.Combine(basePath, "Simple_Asp.Net_Core.xml");


新建資料夾ServiceProvider,增加Swagger擴充套件類

當前Swagger擴充套件類,包含了很多內容,後續會陸續使用上

程式碼如下:


using System;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace Simple_Asp.Net_Core.ServiceProvider
{
   public static class Swagger
   {
       public static void AddSwagger(this IServiceCollection services)
       {
           services.AddSwaggerGen(option =>
           {
               option.SwaggerDoc("v1", new OpenApiInfo
               {
                   Version = "0.0.1",
                   Title = "Simple API",
                   Description = "框架說明文件",
                   TermsOfService = null,
                   Contact = new OpenApiContact { Name = "Simple", Email = string.Empty, Url = null }
               });

               // 讀取xml資訊
               var basePath = AppContext.BaseDirectory;
               var xmlPath = Path.Combine(basePath, "Simple_Asp.Net_Core.xml");
               option.IncludeXmlComments(xmlPath, true);

               // Add security definitions
               option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
               {
                   Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
                   Name = "Authorization",
                   In = ParameterLocation.Header,
                   Type = SecuritySchemeType.ApiKey,
               });
               option.AddSecurityRequirement(new OpenApiSecurityRequirement
               {
                   { new OpenApiSecurityScheme
                   {
                       Reference = new OpenApiReference()
                       {
                           Id = "Bearer",
                           Type = ReferenceType.SecurityScheme
                       }
                   }, Array.Empty<string>() }
               });
           });
       }
   }
}

修改launchSettings.json

目的是讓專案啟動頁為Swagger頁面

新建Controllers資料夾,新增ValuesController

程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Simple_Asp.Net_Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET: api/<ValuesController1>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<ValuesController1>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<ValuesController1>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<ValuesController1>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<ValuesController1>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

執行網站

利用swagger呼叫介面

請求結果返回404的錯誤,發現路由配置錯誤,修改路由配置

再次執行專案,呼叫介面,這一次成功返回訊息!

最後一步取消警告

由於引入了Swagger導致VS多了CS1591警告,也可以不取消此警告

Simple專案的搭建與Swagger配置結束!

總結

Swagger作為前後端分離開發必備工具,不僅可以作為前後端同事交流的文件也有助於我們更直觀的管理API文件。在開發過程中針對Controller的職能與用途,需要做好必要註釋、良好的註釋為前後端交流和後期維護都有很重要的作用。

GitHub原始碼

注意:原始碼除錯過程中如果出現xml檔案路徑錯誤,需要參照Swagger配置“配置XML 文件檔案”步驟,取消勾選然後再選中 ,將XML路徑設定成與你的電腦路徑匹配!

https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 1.Swagger

參考資料

部落格(推薦學習) https://www.cnblogs.com/laozhang-is-phi/p/9495618.html

微軟官方文件 https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-5.0

Swagger官網 https://swagger.io/

相關文章