本人菜鳥,最近想自己從頭開始搭個前後端分離的開發框架,記錄一下:
第一步:新建.Net Core的API項目
以上步驟結束後,一個API項目就創建好了。
第二步:使用Swagger
鼠標右擊下圖所示依賴項,選擇【管理NuGet程序包】
搜索【Swashbuckle.AspNetCore】,安裝Swagger包如下圖:
安裝完畢後,設置項目屬性中的【生成】,把輸出XML勾上,這樣是爲了後續Swagger方便讀取方法等的註釋,
配置完畢後,需要給所有的方法或者類加上註釋,三條斜槓的那種,否則會有警告。
如下圖:
以上步驟結束後,配置Startup文件如下:
/// <summary>
///
/// </summary>
public class Startup
{
/// <summary>
///
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
///
/// </summary>
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
///
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
#region Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v0.1.0",
Title = "SwaggerTest API",
Description = "框架說明文檔",
TermsOfService = "None",
Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "SwaggerTest", Email = "[email protected]", Url = "https://www.xxx.com" }
});
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "SwaggerTest.xml");//這個就是剛剛配置的xml文件名
c.IncludeXmlComments(xmlPath, true);//默認的第二個參數是false,這個是controller的註釋,記得修改
});
#endregion
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
c.RoutePrefix = ""; //路徑配置,設置爲空,表示直接在根域名(localhost:8001)訪問該文件,注意localhost:8001/swagger是訪問不到的,去launchSettings.json把launchUrl去掉
});
#endregion
app.UseMvc();
}
}
最後把項目中【launchSettings.json】裏的初始Url刪掉就可以了,如下圖:
控制器中下圖問題是因爲沒加註釋,加完註釋就OK了
然後編譯運行:
以上就是全部內容了。