.NET Core WebAPI Swagger使用

相对于普通的webapi而言,.net core webapi本身并不具备文档的功能,所以可以借助第三方插件:swagger,使用的话很简单。

步骤一、

Nuget Packages安装,使用程序包管理器控制台,安装命令:Install-Package Swashbuckle.AspNetCore -Pre

步骤二、

在Startup 文件中添加配置:

public void ConfigureServices(IServiceCollection services)
{// Add framework services.
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver
        = new Newtonsoft.Json.Serialization.DefaultContractResolver());//JSON首字母小写解决

    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "MsSystem API"
        });

        //Determine base path for the application.  
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        //Set the comments path for the swagger json and ui.  
        var xmlPath = Path.Combine(basePath, "MsSystem.API.xml");
        options.IncludeXmlComments(xmlPath);
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }


    //app.UseStaticFiles();

    app.UseMvc();

    //app.UseMvc(routes =>
    //{
    //    routes.MapRoute(
    //       name: "default",
    //       template: "api/{controller}/{action}",
    //       defaults: new { controller = "Home", action = "Index" });
    //});

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MsSystem API V1");
    });
}

然后直接访问地址 http://localhost:44632/swagger/

效果图:

 参考地址:

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger

posted on 2017-04-05 10:58  Jade_K  阅读(9447)  评论(1编辑  收藏  举报

导航