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

簡介

《Asp.Net Core3 + Vue3入坑教程》 此教程僅適合新手入門或者先後端分離嘗試者。能夠根據圖文一步一步進操做編碼也能夠選擇直接查看源碼。每一篇文章都有對應的源碼html

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

目錄

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

Asp.Net Core後端項目vue

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

Vue3 前端項目git

暫未發表敬請期待...github

本文簡介

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

Simple項目搭建流程與Swagger配置步驟

新建項目



引入Swagger Nuget包


配置Starup.cs

代碼以下:json

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擴展類,包含了不少內容,後續會陸續使用上api

代碼以下:跨域

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

參考資料

博客(推薦學習) http://www.javashuo.com/article/p-fcwextbq-ec.html

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

Swagger官網 https://swagger.io/

相關文章
相關標籤/搜索