当前位置: 移动技术网 > IT编程>开发语言>.net > 记Asp.Net Core Swagger 使用 并带域接口处理

记Asp.Net Core Swagger 使用 并带域接口处理

2019年03月10日  | 移动技术网IT编程  | 我要评论

引用作者原话:asp.net的webapi中使用swagger作为说明和测试的页面是非常不错的,比起webapitestclient来至少在界面上的很大的提升。但是使用swagger时如果只是一般的控制器直接放到controller下就可以了,而如果因不同的业务需求而需要分类或者有同名的类名时时则没办法很好的处理。

  因为业务需求需要创建域,但是swagger 并未将域添加到接口。所以需要加上以下操作才行。

安装swagger 方法:

    为了大家多看微软官方文档、就直接引用swagger安装及使用方法。 以下是微软官方文档。

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1&tabs=visual-studio

增加域接口显示方法:

 

 

using microsoft.aspnetcore.mvc.apiexplorer;
using system.collections.generic;
using system.linq;
using system.text.regularexpressions;

namespace system.web.http.description
{
    /// <summary>
    /// api描述器扩展
    /// </summary>
    public static class apidescriptionextension
    {
        /// <summary>
        /// 获取区域名称
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        public static list<string> getareaname(this apidescription description)
        {
            string areaname = description.actiondescriptor.routevalues["area"];
            string controlname = description.actiondescriptor.routevalues["controller"];
            list<string> arealist = new list<string>();
            arealist.add(controlname);
            if (!string.isnullorempty(areaname))
            {
                description.relativepath = $"{areaname}/{controlname}/{description.relativepath}";
            } 
            return arealist;
        }
    }
}

通过接口描述扩展获取区域及相关信息进行改写扩展。

 

使用说明:

            services.addswaggergen(c =>
            {
                c.swaggerdoc("v1", new swashbuckle.aspnetcore.swagger.info
                {
                    version = "v1.0.0",
                    title = " api",
                    description = description,
                    termsofservice = "你的公司",
                    contact = new swashbuckle.aspnetcore.swagger.contact { name = "blog.core", email = "blog.core@xxx.com", url = "https://www.jianshu.com/u/94102b59cc2a" }
                    
                });
                //使用域描述
                c.tagactionsby(apidesc => apidesc.getareaname());

                var basepath = platformservices.default.application.applicationbasepath;
                var xmlpath = path.combine(basepath, xmlname);//这个就是刚刚配置的xml文件名
                c.includexmlcomments(xmlpath, true);//默认的第二个参数是false,这个是controller的注释,记得修改
            });

红色部分加入代码即可。

 

结果展示:

 

 

本文章参考 学而时习之进行 更改。  多谢!
作者:_学而时习之_
来源:csdn
原文:https://blog.csdn.net/xxdddail/article/details/81868721
版权声明:本文为博主原创文章,转载请附上博文链接!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网