您现在的位置是:网站首页> 编程资料编程资料
记Asp.Net Core Swagger使用并带域接口处理的方法_实用技巧_
2023-05-24
312人已围观
简介 记Asp.Net Core Swagger使用并带域接口处理的方法_实用技巧_
引用作者原话:Asp.Net的WebApi中使用Swagger作为说明和测试的页面是非常不错的,比起WebApiTestClient来至少在界面上的很大的提升。但是使用Swagger时如果只是一般的控制器直接放到Controller下就可以了,而如果因不同的业务需求而需要分类或者有同名的类名时时则没办法很好的处理。
因为业务需求需要创建域,但是Swagger并未将域添加到接口。所以需要加上以下操作才行。
安装Swagger方法:
为了大家多看微软官方文档、就直接引用Swagger安装及使用方法。以下是微软官方文档。
增加域接口显示方法:
using Microsoft.AspNetCore.Mvc.ApiExplorer; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace System.Web.Http.Description { /// /// API描述器扩展 /// public static class ApiDescriptionExtension { /// /// 获取区域名称 /// /// /// public static List GetAreaName(this ApiDescription description) { string areaName = description.ActionDescriptor.RouteValues["area"]; string controlName = description.ActionDescriptor.RouteValues["controller"]; List areaList = new List(); 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的注释,记得修改 });红色部分加入代码即可。
结果展示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- .net core中Quartz的使用方法_实用技巧_
- Asp.Net Core基于JWT认证的数据接口网关实例代码_实用技巧_
- 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序报错的解决办法_实用技巧_
- asp.net上传Excel文件并读取数据的实现方法_实用技巧_
- 详解.NET Core 使用HttpClient SSL请求出错的解决办法_实用技巧_
- .Net Core自定义配置源从配置中心读取配置的方法_实用技巧_
- ASP.NET Core实现单体程序的事件发布/订阅详解_实用技巧_
- DotNetCore深入了解之HttpClientFactory类详解_实用技巧_
- Asp.Net Core2.1前后使用HttpClient的两种方式_实用技巧_
- Asp.Net Core对接钉钉群机器人的完整步骤记录_实用技巧_
