【问题标题】:How do I get Swagger+Swashbuckle to show endpoints?如何让 Swagger+Swashbuckle 显示端点?
【发布时间】:2017-10-30 13:38:33
【问题描述】:

我正在尝试将 swagger+swashbuckle 添加到我的 ASP.NET Core 项目中。我可以启动并运行 Swagger UI,但它完全是空的。我试着四处寻找,在https://github.com/domaindrivendev/Swashbuckle/issues/1058 发现了一个类似的问题。这让我觉得可能是路由问题,所以我尝试使用[Route("testroute")] 给我的控制器一个显式路由而不是类。这使得我添加了一条路线的端点可以毫无问题地显示出来。

由于向每个端点添加显式路由不是最佳选择,我做错了什么以及如何修复它以大摇大摆地显示我的所有端点?

我的创业公司,其中集成了 swagger

    public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json", optional: true , reloadOnChange: true);

        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.AddMvc().AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });

        services.AddDbContext<PromotionContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:Jasmine"]));
        services.AddTransient<PromotionDbInitializer>();
        services.AddTransient<IComponentHelper, ComponentHelper>();
        services.AddTransient<IComponentFileHelper, ComponentFileHelper>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, PromotionDbInitializer promotionSeeder)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });



        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Promotion}/{action=Index}/{id?}");
        });

       //Because there is not a seed method built into the EF migrations pipeline in EFCore this seeding method will interfere with the migrations when attempting to deploy the database
       //uncomment if you need to seed

       //promotionSeeder.Seed().Wait();
    }
}

我的控制器,GetAll 和 Post 方法显示在 testroute 和 testFormRoute 下的 swagger ui 页面上,但 Get 和 Delete 方法没有显示

public class PromotionController : Controller
{
    private PromotionContext context;
    public PromotionController(PromotionContext _context)
    {
        context = _context;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    [Route("testroute")]
    public IActionResult GetAll()
    {
        try
        {
            var result = context.Promotions
                            .Include(promotion => promotion.CombinabilityType)
                            .Include(promotion => promotion.ValueType)
                            .Include(promotion => promotion.Currency)
                            .Include(promotion => promotion.Components)
                                .ThenInclude(component => component.TargetType)
                            .ToList();
            return Ok(result);
        }
        catch(Exception ex)
        {
            return StatusCode(500);
        }
    }


    public IActionResult Get(string promoCode)
    {
        try
        {
            var result = context.Promotions
                                .Include(promotion => promotion.CombinabilityType)
                                .Include(promotion => promotion.ValueType)
                                .Include(promotion => promotion.Currency)
                                .Include(promotion => promotion.Components)
                                    .ThenInclude(component => component.TargetType)
                                .FirstOrDefault(x => x.PromoCode == promoCode);
            return Ok(result);
        }
        catch(Exception ex)
        {
            return StatusCode(500);
        }
    }

    [HttpPost]
    [Route("testFormRoute")]
    public IActionResult Post([FromForm] Promotion newPromotion)
    {
        try
        {
            context.Promotions.Add(newPromotion);
            context.SaveChanges();
        }
        catch(DbUpdateException ex)
        {
            return StatusCode(500);
        }

        return Ok();
    }

    [HttpDelete]
    public IActionResult Delete(string promoCode)
    {
        try
        {
            var promotion = context.Promotions.FirstOrDefault(x => x.PromoCode == promoCode);

            if(promotion != null)
            {
                context.Promotions.Remove(promotion);
                context.SaveChanges();
            }
        }
        catch(DbUpdateException ex)
        {
            return StatusCode(500);
        }

        return Ok();
    }
}

【问题讨论】:

    标签: c# asp.net-core swagger swagger-ui swashbuckle


    【解决方案1】:

    为你的控制器添加路由属性:

    [Route("[controller]/[action]")]
    public class PromotionController : Controller
    {
    ...
    

    并为您的操作设置 HttpGet 属性:

    [HttpGet]
    public IActionResult GetAll()
    {
    ...
    
    [HttpGet("{promoCode}")]
    public IActionResult Get(string promoCode)
    {
    ...
    

    您必须小心混合和匹配静态和动态路由的方式。查看 this article 了解更多关于 asp.net 核心中基于属性的路由的详细信息。

    【讨论】:

    • 那行得通。我通读了这篇文章,但我不明白为什么它会起作用。据我所知,这将我在启动时设置的路线移动到类和方法的属性中。你知道为什么 swashbuckle/swagger 不能处理默认路由吗?
    • 我实际上不确定 Swashbuckle 是否仅正确处理用于生成文档的默认 MVC 路由。我倾向于使用属性路由结合 XML 文档来生成我的 swagger ui。
    【解决方案2】:

    尝试改变

    public class PromotionController : Controller
    

    public class PromotionController : ApiController
    

    【讨论】:

    • 这是 ASP.NET Core 所以没有 ApiController,mvc 和 webapi 库已经合并,只有 Controller 类
    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2016-08-06
    • 2018-08-24
    • 2018-02-01
    相关资源
    最近更新 更多