swagger的配置

  // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                    new Info
                    {
                        Title = "API接口文档",
                        Version = "v1",
                        Description = "开发接口调试.",
                        Contact = new Contact
                        {
                            Name = "ListXiong",
                            Email = "",
                        },
                        TermsOfService = "None"
                    }
                 );
                 //注释
                c.IncludeXmlComments(GetXmlCommentsPath());
            });

            services.AddSupportServices();
          
        }

        // 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();
            }
           
            app.UseMvc();
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "doc/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "doc";
                c.SwaggerEndpoint("/doc/v1/swagger.json", "API v1");
            });
            app.UseStaticFiles();
        }
        /// <summary>
        /// 获取XML文档地址
        /// </summary>
        /// <returns></returns>
        private string GetXmlCommentsPath()
        {
            var app = PlatformServices.Default.Application;
            return Path.Combine(app.ApplicationBasePath, Path.ChangeExtension(app.ApplicationName, "xml"));
        }            

 

转载于:https://www.cnblogs.com/AnAng/p/9203782.html

### 配置 Swagger 在项目中的使用 在 Spring Boot 项目中,可以通过多种方式配置 Swagger 来生成和管理 API 文档。以下是详细的配置步骤: #### 1. 引入依赖 首先,在项目的 `pom.xml` 文件中添加 Swagger 的依赖。通常使用的是 `springfox-swagger2` 和 `springfox-swagger-ui` 库[^2]。 ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` #### 2. 创建 Swagger 配置类 接下来,创建一个 Java 配置类来启用和配置 Swagger。该类需要与 Spring Boot 的启动类处于同一层级或其子包中。 ```java package org.springboot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.annotations.ApiOperation; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build(); } } ``` 上述代码启用了 Swagger,并通过 `Docket` Bean 定义了文档的生成规则。这里选择仅扫描带有 `@ApiOperation` 注解的方法 [^4]。 #### 3. 配置跨域支持(可选) 如果前端应用与后端服务不在同一个域名下,需要配置跨域支持。可以在 `SwaggerConfig` 类中添加以下方法: ```java @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/v2/api-docs/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); } }; } ``` #### 4. 使用 Swagger 注解 在控制器类和方法上使用 Swagger 注解,以提供更详细的文档信息。常见的注解包括: - **`@ApiModel`**:用于描述模型对象。 - **`@ApiModelProperty`**:用于描述模型属性。 - **`@Api`**:用于描述控制器类的功能。 - **`@ApiOperation`**:用于描述具体的操作。 示例代码如下: ```java @Api(tags = "用户信息") @RestController @RequestMapping("/users") public class UserController { @ApiOperation(value = "查询用户详细信息") @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { // 方法实现 } } ``` #### 5. 启动并访问 Swagger UI 完成上述配置后,启动 Spring Boot 应用程序,并通过以下 URL 访问 Swagger UI: ``` http://localhost:8080/swagger-ui.html ``` 在这个界面中,可以查看所有已定义的 API 接口,并进行测试。 #### 6. 安全控制(可选) 为了增强安全性,可以为 Swagger 配置权限验证。例如,使用 Spring Security 对 `/swagger-ui.html` 路径进行保护: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html").authenticated() .and() .httpBasic(); // 使用 HTTP Basic 认证 } } ``` 通过这种方式,只有经过认证的用户才能访问 Swagger UI 界面 [^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值