c# webapi swagger

如何配置swagger?

在使用项目中,咱们但愿去查看咱们的webapi的测试,那么咱们是须要去有一个集成的测试的。web

步骤

1.在nutget管理包中下载swagger包。api

2.这样会在App_start 文件夹中出现swaggerconfig.cs 和swaggerNet.cs,
这个时候就须要配置的时候了。restful

3.取消下面的注释(swaggerconfig.cs)ide

c.IncludeXmlComments(string.Format("{0}/bin/ThinkingSpace.XML", System.AppDomain.CurrentDomain.BaseDirectory));

固然咱们为了代码的模块化,能够封装到一个方法中:模块化

private static string GetXmlCommentsPath()
{
    return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\GetDocumentation.XML";
}

好吧,ok,咱们知道了这个配置了。测试

那么咱们须要再bin目录下建立一个xml,推荐是项目名.xml.ui

4.那么接下来就是swaggerNet.cs配置.spa

using System;
using System.IO;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Dispatcher;
using System.Web.Routing;
using Swagger.Net;

[assembly: WebActivator.PreApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PreStart")]
[assembly: WebActivator.PostApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PostStart")]
namespace ThinkingSpace.App_Start 
{
    public static class SwaggerNet 
    {
        public static void PreStart() 
        {
            RouteTable.Routes.MapHttpRoute(
                name: "SwaggerApi",
                routeTemplate: "api/docs/{controller}",
                defaults: new { swagger = true }
            );            
        }
        
        public static void PostStart() 
        {
            var config = GlobalConfiguration.Configuration;

            config.Filters.Add(new SwaggerActionFilter());
            
            try
            {
                config.Services.Replace(typeof(IDocumentationProvider),
                    new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/ThinkingSpace.XML")));
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Please enable \"XML documentation file\" in project properties with default (bin\\ThinkingSpace.XML) value or edit value in App_Start\\SwaggerNet.cs");
            }
        }
    }
}

统一咱们须要修改xml的位置便可。.net

注意

咱们须要在webapi中只能存在一个get,不然会报错,由于须要符合restful 标准。rest

一个controller中只能有一个HttpGet请求,多了就会报错。建议减小重载方法,将其余Get方法分开

若是在swagger.config中加上c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());则会只显示第一个get方法

另:能够不安装swagger ui for .net,安了有可能会报错

相关文章
相关标签/搜索