栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

引用作者原话: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
{
  /// 
  /// 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的注释,记得修改
      });

红色部分加入代码即可。

结果展示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/55138.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号