Fork me on GitHub

ASP.NET Core 1.0 中使用 Swagger 生成文档

github:https://github.com/domaindrivendev/Ahoy

之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1.0中同样也支持。

依赖包

"dependencies": {
    "Swashbuckle.SwaggerGen": "6.0.0-rc1-final",
    "Swashbuckle.SwaggerUi": "6.0.0-rc1-final"
  }

项目属性选中“生成时生成输出”选项用来生成XML注释

Startup类

复制代码
public class Startup
    {
        //private readonly string pathXml = @"\\Mac\Home\Desktop\asp.net core\learn_asp.net core 1.0\artifacts\bin\SwaggerForASP.NETCore\Debug\dnx451\SwaggerForASP.NETCore1.0.xml";
        private readonly string pathXml = @"C:\Users\irving\Desktop\asp.net core\LearningASP.NETCore\artifacts\bin\LearningASP.NETCore\Debug\dnx451\LearningASP.NETCore.xml";

        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSwaggerGen();

            services.ConfigureSwaggerDocument(options =>
            {
                options.SingleApiVersion(new Info
                {
                    License = new License { Name = "irving", Url = @"http://cnblogs.com/irving" },
                    Contact = new Contact { Name = "irving", Email = "zhouyongtao@outlook.com", Url = @"http://cnblogs.com/irving" },
                    Version = "v1",
                    Title = "ASP.NET Core 1.0 WebAPI",
                    Description = "A Simple For ASP.NET Core 1.0 WebAPI",
                    TermsOfService = "None"
                });
                options.OperationFilter(new ApplyXmlActionComments(pathXml));
            });

            services.ConfigureSwaggerSchema(options =>
            {
                options.IgnoreObsoleteProperties = true;
                options.DescribeAllEnumsAsStrings = true;
                options.ModelFilter(new ApplyXmlTypeComments(pathXml));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

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

            app.UseSwaggerGen();

            app.UseSwaggerUi();
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
复制代码
OrdersController类
复制代码
    [Route("api/orders")]
    public class OrdersController : Controller
    {
        [HttpGet]
        [Route("info")]
        public async Task<ActionResult> Info()
        {
            return await Task.Run(() =>
            {
                return Json(new { name = "irving", age = 25 });
            }).ContinueWith(t => t.Result);
        }

        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
复制代码

访问:http://localhost/swagger/ui/index.html

image

REFER:
http://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/
https://api.gitcafe.com/apidoc/
Swagger框架学习分享
http://blog.csdn.net/u010827436/article/details/44417637
Micro Service工具集之Swagger:可测试的样式化API文档
http://ningandjiao.iteye.com/blog/1948874

https://github.com/aspnet/Docs/blob/master/aspnetcore/tutorials/web-api-help-pages-using-swagger.md

https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1

posted @   花儿笑弯了腰  阅读(2974)  评论(3编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示