.NET Core3.1 WebApi 配置Swagger 超詳細辦法

原由是這樣的

大概上個月的時候作的一個項目,想試試配置swagger,由於現有項目配置的swagger只有.NET Framework上配置過,core上的還要從新學,而後網上一堆教程,各個方法不一樣,這一配置就是兩天,可苦死我了。到如今,又開了個新項目的時候,果斷搭建swagger,結果發現好像不會搭了,要弄些啥來着???又浪費了一個小時回頭看之前的項目,=-=,這還了得,我仍是寫成博客放上面吧html

廢話很少說,直接開始配置

首先安裝NuGet包 Swashbuckle.AspNetCore
json

緊接着 Startup 的代碼api

using Swashbuckle.AspNetCore.SwaggerUI;//要添加的命名空間

namespace Project.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc("v1", new OpenApiInfo() { Title = "項目名稱 Api", Version = "v1" });//項目名稱填你的項目名稱,下同
                config.CustomSchemaIds(type => type.FullName);
                config.IncludeXmlComments($"{AppDomain.CurrentDomain.BaseDirectory}/Project.API.xml");//Project.API 爲你的項目名稱
            });
            Register(services);

            services.AddOptions();


        }

        /// <summary>
        /// 依賴注入
        /// </summary>
        /// <param name="services"></param>
        private static void Register(IServiceCollection services)
        {


        }

        // 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.UseHttpsRedirection();

            app.UseSwagger(c =>
            {
                c.RouteTemplate = "api-doc/{documentName}/swagger.json";//配置後,你的最終訪問路徑就就是 /api-doc/index.html
            });
            app.UseSwaggerUI(c =>
            {
                c.InjectJavascript("/zh_CN.js");//中文包,怎麼測試也出不來,等待一個大佬解決下,因此這裏就不放中文包了,由於根本用不了,(這句能夠刪
                c.ShowExtensions();
                c.DocExpansion(DocExpansion.None);
                c.RoutePrefix = "api-doc";
                c.SwaggerEndpoint("v1/swagger.json", "項目名稱 Api v1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=ApiHome}/{action=Index}/{id?}");
            });
        }
    }
}

最後兩步
你的項目-->右鍵屬性-->生成事件-->生成後事件命令行--> copy $(TargetDir){項目名稱}.xml $(ProjectDir){項目名稱}.xml
app

你的項目-->右鍵屬性-->生成事件-->生成後事件命令行--> 輸出 如圖所示
測試

最後運行試試

記得切換端口號 https://localhost:{xxxx}/api-doc/index.htmlui

成功!!!

相關文章
相關標籤/搜索