netcore配置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 = "[email protected]", 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 = "[email protected]", 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写入注释也是一样的)

贴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
        }
    }

猜你喜欢

转载自www.cnblogs.com/flames/p/11401902.html