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


起因是這樣的

大概上個月的時候做的一個項目,想試試配置swagger,因為現有項目配置的swagger只有.NET Framework上配置過,core上的還要重新學,然后網上一堆教程,各個方法不同,這一配置就是兩天,可苦死我了。到現在,又開了個新項目的時候,果斷搭建swagger,結果發現好像不會搭了,要弄些啥來着???又浪費了一個小時回頭看以前的項目,=-=,這還了得,我還是寫成博客放上面吧

廢話不多說,直接開始配置

首先安裝NuGet包 Swashbuckle.AspNetCore

緊接着 Startup 的代碼

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

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

最后運行試試

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

成功!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM