EF WebApi搭配Swagger

API搭配Swagger可以更好的展示API中的接口方法和参数,也可以脱离其他测试工具,比如Postman进行测试

这里是EntityFramework搭配Swagger

1.安装 nuget包  Swashbuckle

安装完后会发现App_Start下面多了一个Class文件

2.可以把里面那些注释掉的内容全部删除,只剩下下面这些内容

 public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {                      
                        c.SingleApiVersion("v1", "EFWebApi");

                    })
                .EnableSwaggerUi(c =>
                    {                     
                    });
        }
    }

3.添加下面这个方法 GetXmlCommentsPath

 public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {                      
                        c.SingleApiVersion("v1", "EFWebApi");

                    })
                .EnableSwaggerUi(c =>
                    {                     
                    });
        }

        private static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\bin\EFWebApi.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }
    }

这个是为了在页面上生成注释的,我们可以注释这个接口方法的作用是什么,它的参数是什么,等等等等

4.然后右键项目,属性-->生成-->点上xml文档那个按钮

5.然后把相关配置可以 集中配置到WebApiConfig中

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.RegistSwagger();//添加这个swagger的Regist
        }
        private static void RegistSwagger(this HttpConfiguration config)
        {
            config.EnableSwagger("docs/{apiVersion}/swagger", c =>
            {
                c.SingleApiVersion("v1", "WebApplication1");
                c.IncludeXmlComments(GetXmlCommentsPath());
            })
   .EnableSwaggerUi("apis/{*assetPath}");//原本进入的地址是/swagger/ui/index 这样就能换地址成/apis/index 
        }
        private static string GetXmlCommentsPath()
        {
            return $@"{AppDomain.CurrentDomain.RelativeSearchPath}\WebApplication2.XML";
        }
    }

运行起来效果如下,记得默认URL可以改一下

发布了45 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36730649/article/details/96752576
EF
今日推荐