【问题标题】:Simple Swagger generation with Swashbuckle使用 Swashbuckle 生成简单的 Swagger
【发布时间】:2020-10-30 03:58:22
【问题描述】:

我需要为另一个项目创建一些 Swagger 文档,所以我想用 Swashbuckle 快速完成它以节省一些时间。在 Visual Studio 中,我使用 ASP.NET Core WEB 应用程序创建了一个新项目,并选择了模型-视图-控制器模板。然后我通过 Nuget 安装了 Swashbuckle 并将模板值更改为:

程序.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs

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

        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
                .AddControllers()
                .AddJsonOptions(x =>
                {
                    x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                    x.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                });

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                x.DescribeAllParametersInCamelCase();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(xmlPath);
            });
        }

        // 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.UseSwagger(x => x.SerializeAsV2 = true);

            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
                x.RoutePrefix = string.Empty;
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

控制器/ApiController.cs

[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
[Route("api/MyApi/v1/")]
public class ApiController : Controller
{

    /// <summary>
    ///     Gets something as bytes for the given <paramref Id="id"/>.
    /// </summary>
    /// <returns>A result object indicating success or failure.</returns>
    /// <response code="200">The request succeeded.</response>
    /// <response code="400">
    ///     At least one of the following issues occurred:
    ///     - Error
    /// </response>
    /// <response code="500">An unexpected error occurred.</response>
    [HttpGet("{id}")]
    public static Task<Result> GetSomething(string id)
    {
        return new Task<Result>(null, "");
    }
}

现在,当我启动 API 并看到招摇时,我得到了“我的 API”名称,但没有端点:

No operations defined in spec!

为什么这不起作用?

【问题讨论】:

    标签: c# swagger swashbuckle


    【解决方案1】:

    我想你也需要services.AddMvcCore()...

    【讨论】:

    • 刚试了下,好像没什么效果。我在这里按照教程进行操作:docs.microsoft.com/en-us/aspnet/core/tutorials/…
    • 如果您暂时忘记了 swagger,您是否检查过您的端点是否确实在工作? :)
    • 嗯实际上没有,我去的时候得到 404:localhost:58700/api/MyApi/v1/1
    • 嗯,我创建了一个新项目,做了同样的事情,现在它可以工作了......
    • 我收回了。似乎默认的“WeatherForecastController”确实有效,但是一旦我开始添加我自己的它就不起作用了。
    猜你喜欢
    • 2021-04-13
    • 2016-07-11
    • 1970-01-01
    • 2019-12-23
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多