簡介
《Asp.Net Core3 + Vue3入坑教程》 此教程適合新手入門或者前后端分離嘗試者。可以根據圖文一步一步進操作編碼也可以選擇直接查看源碼。每一篇文章都有對應的源碼
教程后期會將 .Net Core 3升級成 .Net Core 5
目錄
《Asp.Net Core3 + Vue3入坑教程》系列教程目錄
Asp.Net Core后端項目
- (本文)后端項目搭建與Swagger配置步驟
- 配置CROS策略解決跨域問題
- AutoMapper & Restful API & DI
- EF Core & Postgresql
- .Net Core 3升級成 .Net 5 & JWT
- (推薦)異常處理與UserFriendlyException
- ...
Vue3 前端項目
- 使用vue-cli創建vue項目
- 使用Ant Design of Vue編寫頁面 & vue-router 初試
- (暫未發表敬請期待...)將Antd導航菜單與vue-router綁定
- (暫未發表敬請期待...) 保存用戶登入狀態vuex初試
暫未發表敬請期待...
本文簡介
本文為《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/