首页 文章

如何让Swagger Swashbuckle显示 endpoints ?

提问于
浏览
0

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

由于向每个 endpoints 添加显式路由是非最佳的,我做错了什么以及如何修复它以获得显示所有 endpoints 的招摇?

我的创业公司集成了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();
    }
}

2 回答

  • -1

    向控制器添加路由属性:

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

    并在您的操作上设置HttpGet属性:

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

    你必须要小心如何混合和匹配静态和动态路由 . 有关asp.net核心中基于属性的路由的更多详细信息,请查看this article .

  • 2

    尝试改变

    public class PromotionController : Controller
    

    public class PromotionController : ApiController
    

相关问题