創建一個webapi項目


修改launchSettings.json
將launchSettings.json中的IIS啟動刪掉。別問我為啥 原因就是IISEXPRESS有時候需要我手動重啟。我嫌麻煩。
刪除后的代碼就 變成了這個樣子
{
"profiles": {
"MsgWebApi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:62827/"
}
}
}
F6運行一下,修復一下DLL和看看有沒有錯誤
為Web Api添加Swagger幫助頁面
完全依照官方文檔安裝swagger即可: https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
這部分就寫了。寫一個通過nuget安裝的方法。
Install-Package Swashbuckle.AspNetCore
如下圖

在Startup的ConfigureServices注冊並配置Swagger, 然后在StartUp的Configure方法使用Swagger中間件:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
好了 。第一次運行F5跑起來吧。
http://localhost:62827/swagger/index.html 訪問地址是:url地址+swagger+index.html看不懂的話。就看不懂吧。
運行效果如下。

后續
.net core qq群:136724480
