.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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM