Net Core使用Swagger

  • Nuget Swashbuckle.AspNetCore
  • 配置信息如下,使用XML记得【右键项目】->【属性】->【生成】->勾选XML文档文件
public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "HelloCore Api",
                    Version = "v1",
                    Description = "HelloCore Api",
                    Contact = new Contact { Name = "boy", Url = "www.baidu.com", Email = "111111@qq.com" },
                    TermsOfService = "暂无"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }


            app.UseStaticFiles();
            app.UseCookiePolicy();

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

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    /// <summary>
    /// 测试类
    /// </summary>
    public class Test
    {
        public Test(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
    }
    /// <summary>
    /// 测试Api
    /// </summary>
    [Route("TestApi")]
    public class TestApiController : Controller
    {

        /// <summary>
        /// 测试Index1
        /// </summary>
        /// <remarks>
        /// Sample request:
        ///
        ///     POST /Todo
        ///     {
        ///        "id": 1,
        ///        "name": "Item1",
        ///        "isComplete": true
        ///     }
        ///
        /// </remarks>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        /// <response code="201">Returns the newly created item</response>
        /// <response code="400">If the item is null</response>
        [HttpPost("Index1", Order = 1)]
        [ProducesResponseType(typeof(Test), 200)]//输出类型
        [ProducesResponseType(201)]
        [ProducesResponseType(400)]
        [Produces("application/json")]//限定输出类型
        public async Task<IActionResult> Index1([FromBody]Test viewModel)
        {
            return Ok(new Test(viewModel.Name, viewModel.Age));
        }

        /// <summary>
        /// 测试Index2
        /// </summary>
        /// <returns></returns>
        [HttpGet("Index2", Order = 2)]
        [ApiExplorerSettings(IgnoreApi = true)]//忽略该Api
        public async Task<IActionResult> Index2()
        {
            var str = "Hello Core2";
            return Ok(new { str });
        }
    }
posted @ 2018-07-20 15:21  the boy、图样图森破  阅读(253)  评论(0)    收藏  举报