.NET CORE 3.1 WEBAPI项目中配置SWAGGER问题

.NET CORE 3.1 WEBAPI项目中配置SWAGGER问题

问题描述:

我在学习.NET CORE 3.1 WEBAPI项目中配置SWAGGER,最后并没有出来想要的界面(界面如下图),不知道如何处理,向各位专家请教。

另外,在我程序中,有好几个Controllers页(例如:BindingWechatController,CustomerController,WeatherForecastController等等),程序是怎么知道应该调用哪个页面的呢?

代码:


```c#
namespace expressApi
{
    public class Startup
    {
        ///// <summary>
        ///// </summary>
        //public static ILoggerRepository repository { get; set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="services"></param>
        // 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(m => m.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "expressApi",  //标题
                Version = "v1",
                Description = $".net core Http API v1"    //描述
            })
            );
        }
        private static void Register(IServiceCollection services)
        {
        }
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // 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.UseRouting();

            app.UseAuthorization();
            app.UseSwagger();
            app.UseSwaggerUI(m => m.SwaggerEndpoint("/swagger/v1/swagger.json", "expressApi"));


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

```

问题界面

img

题主检查下所有Controller文件中是否存在其他public方法,一般controller中public的方法是对外提供服务的

启用swagger后Controller中只能有一个HttpPost和HttpGet(如果没有加HttpPost/HttpGet属性,默认为HttpGet)的public方法,如果存在多个swagger会不知道调用这个controller下的哪个方法
比如下面这个


namespace webapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class uploadFileController : ControllerBase
    {

        [HttpPost]
        public IActionResult upload([FromBody] Dictionary<string, string> fileDTO)
        {

            return Content("POST");
        }
        [HttpGet("Get")]
        public IActionResult Get()
        {

            return Content("test");
        }

        public string Get1() { return "Get1"; }
    }
}


存在2个HttpGet属性的方法(Get1没有申明),会导致swagger出错不知道显示哪个,但是对于webapi项目来说是没有问题的。

img

第一个get可以通过/uploadfile/get访问,第二个用/uploadfile

去掉其中一个或者改为private就正常显示了

img