netcore配置swagger


 搭新項目的時候經常開老項目看配置代碼,感覺麻煩,而且每次遇到問題不一定記得住,就想把之前搭建項目遇到的問題記錄下來。比如配置swagger

 Nuget 安裝 Swashbuckle.AspNetCore

啟動項 Startup.cs 中 注冊swagger

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v0.1.0",
                    Title = "yaqa.Core API",
                    Description = "框架說明文檔",
                    TermsOfService = "None",
                    Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "yaqa.Core", Email = "yaqa.Core@xxx.com", Url = "" }
                });
            });

            #endregion
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            #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": "swagger/index.html"去掉, 然后直接訪問localhost:8001/index.html即可
            });
            #endregion

            app.UseHttpsRedirection();
            app.UseMvc();
        }

F5運行項目,到了api/values 接口 ,但是我想直接到swagger頁面就得輸入/swagger.太麻煩

更改默認啟動路徑為swagger 就不用每次打開重新路由了。

 

然后為接口添加注釋:

代碼接口寫上注釋,然后添加讀取注釋服務。由於生產的xml我默認的是根目錄,所以下面讀取注釋就按照根目錄路徑讀取xml.

 
         
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v0.1.0", Title = "yaqa.Core API", Description = "框架說明文檔", TermsOfService = "None", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "yaqa.Core", Email = "yaqa.Core@xxx.com", Url = "" } }); });

      //添加讀取注釋服務 var basePath = _hostingEnvironment.ContentRootPath; var xmlPath = Path.Combine(basePath, "szApi.xml"); var entityXmlPath = Path.Combine(basePath, "Jum.Entity.xml"); //var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.XML"; c.IncludeXmlComments(xmlPath, true); c.IncludeXmlComments(entityXmlPath, true);
#endregion 
}


按F5運行 可以看到注釋.  (對Model寫入注釋也是一樣的)

代碼里沒注釋的地方好多警告,看起來超級不爽。

加上;1591就可以了

 

瞬間清爽很多.

現在貼上Startup.cs全代碼加注釋 便於以后項目可以直接參考:

public class Startup
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            //Configuration = configuration;
            _hostingEnvironment = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

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

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//設置時間格式
            });
            // 注冊全局
            services.AddMvc(o =>
            {
                o.Filters.Add(typeof(GlobalExceptionFilter));
            });

            // 注冊配置文件
            services.AddOptions();
            //services.AddOptions().Configure<JwtAuthConfigModel>(Configuration.GetSection("JwtSettings"));
            services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));
            services.Configure<YZSetting>(Configuration.GetSection("YZSetting"));
            //模型綁定 特性驗證,自定義返回格式
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //獲取驗證失敗的模型字段 
                    var errors = actionContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();
                    var str = string.Join("|", errors);
                    //設置返回內容
                    var result = new MessageModel
                    {
                        success = false,
                        msg = str
                    };
                    return new BadRequestObjectResult(result);
                };
            });
            
        // 注冊服務
            services.AddTransient<IEntity, EntityService>();//// 注冊緩存
            //services.AddSingleton<IMemoryCache>(factory =>
            //{
            //    var cache = new MemoryCache(new MemoryCacheOptions());
            //    return cache;
            //});

            #region CORS 
            services.AddCors(c =>
            {
                c.AddPolicy("AllowAnyOrigin", policy =>
                {
                    policy.AllowAnyOrigin()//允許任何源
                    .AllowAnyMethod()//允許任何方式
                    .AllowAnyHeader()//允許任何頭
                    .AllowCredentials();//允許cookie
                });
                c.AddPolicy("AllowSpecificOrigin", policy =>
                {
                    policy.WithOrigins("http://xxxx:80")
                    .WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .WithHeaders("authorization");
                });
            });
            #endregion


            #region 注冊Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1.1.0",
                    Title = "sz WebAPI",
                    Description = "框架集合",
                    TermsOfService = "None",
                    Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Jumper", Email = "", Url = "" }
                });
                //添加讀取注釋服務
                var basePath = _hostingEnvironment.ContentRootPath;
                var xmlPath = Path.Combine(basePath, "szApi.xml");
                var entityXmlPath = Path.Combine(basePath, "Jum.Entity.xml");
                //var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.XML";
                c.IncludeXmlComments(xmlPath, true);
                c.IncludeXmlComments(entityXmlPath, true);

                // 為swagger添加header驗證信息
                var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
                c.AddSecurityRequirement(security);//添加一個必須的全局安全信息,和AddSecurityDefinition方法指定的方案名稱要一致,這里是Bearer。
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT授權(數據將在請求頭中進行傳輸) 參數結構: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",//jwt默認的參數名稱
                    In = "header",//jwt默認存放Authorization信息的位置(請求頭中)
                    Type = "apiKey"
                });

            });

            #endregion
        }

        // 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();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            // 注冊中間件
            app.UseMiddleware<JwtAuthorizationFilter>();
            app.UseCors("AllowAnyOrigin");
            // HTTP 重定向
            app.UseHttpsRedirection();
            app.UseMvc();
       // 靜態文件
            app.UseStaticFiles();
            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
            });
            #endregion
        }
    }

 


免責聲明!

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



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