Swagger使用教程 SwashbuckleEx (2)

// 处理默认路由以及区域路由问题
private static bool ResolveAreasSupportByRouteConstraint(ApiDescription apiDescription, string targetApiVersion)
{
if (targetApiVersion == "v1")
{
return apiDescription.Route.RouteTemplate.StartsWith("api/{controller}");
}
var routeTemplateStart = "api/" + targetApiVersion;
return apiDescription.Route.RouteTemplate.StartsWith(routeTemplateStart);
}

## 4.5 区域文档过滤 用于区分每个区域内文档切换问题,仅供参考,因为里面调整的内容与命名空间`.`相关。

///
/// 添加 Area 文档过滤器
///
public class AddAreasSupportDocumentFilter:IDocumentFilter
{
///
/// 配置
///
private readonly SwaggerConfiguration _config = ConfigProvider.Default.GetConfiguration();

/// <summary> /// 重写Apply方法,加入Area文档处理 /// </summary> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { IDictionary<string,PathItem> replacePaths=new ConcurrentDictionary<string, PathItem>(); foreach (var item in swaggerDoc.paths) { // api/Areas/Namespace.Controller/Action string key = item.Key; if (key.Contains(_config.JwtRoute)) { replacePaths.Add(item.Key,item.Value); continue; } var value = item.Value; var keys = key.Split('http://www.likecs.com/'); // Areas路由:keys[0]:"",keys[1]:api,keys[2]:Areas,keys[3]:{ProjectName}.Api.Areas.{AreaName}.Controllers.{ControllerName}Controller,keys[4]:{ActionName} if (keys[3].IndexOf('.') != -1) { // 区域路径 string areaName = keys[2]; string namespaceFullName = keys[3]; var directoryNames = namespaceFullName.Split('.'); string namespaceName = directoryNames[3]; if (areaName.Equals(namespaceName, StringComparison.OrdinalIgnoreCase)) { string controllerName = directoryNames[5]; replacePaths.Add( item.Key.Replace(namespaceFullName, controllerName.Substring(0, controllerName.Length - DefaultHttpControllerSelector.ControllerSuffix.Length)), value); } } // 通用路由:keys[0]:"",keys[1]:api,keys[2]:{ProjectName}.Api.Controllers.{ControllerName}Controller,keys[3]:{ActionName} else if (keys[2].IndexOf('.') != -1) { // 基础路径 string namespaceFullName = keys[2]; var directoryNames = namespaceFullName.Split('.'); bool isControllers = directoryNames[2].Equals("Controllers", StringComparison.OrdinalIgnoreCase); string controllerName = directoryNames[3]; if (isControllers) { replacePaths.Add( item.Key.Replace(namespaceFullName, controllerName.Substring(0, controllerName.Length - DefaultHttpControllerSelector.ControllerSuffix.Length)), value); } } swaggerDoc.paths = replacePaths; } }

}

## 4.6 显示上传文件参数 SwaggerUI 有上传文件的功能,与添加自定义`HTTP Header`做法相类似,我们可以通过特性来标识API是否具有上传功能。

///
/// 添加 上传操作过滤
///
public class AddUploadOperationFilter:IOperationFilter
{
///
/// 重写Apply方法,加入Upload操作过滤
///
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var upload = apiDescription.ActionDescriptor.GetCustomAttributes().FirstOrDefault();
if (upload == null)
{
return;
}
operation.consumes.Add("application/form-data");
operation.parameters.Add(new Parameter()
{
name = upload.Name,
@in = "formData",
required = upload.Require,
type = "file",
description = upload.Description
});
}
}

///
/// 上传属性,用于标识接口是否包含上传信息参数
///
public class UploadAttribute:Attribute
{
///
/// 参数名
///
public string Name { get; set; } = "file";

/// <summary> /// 是否必须包含文件 /// </summary> public bool Require { get; set; } = true; /// <summary> /// 备注 /// </summary> public string Description { get; set; } = "";

}

然后再`SwaggerConfig.cs`的`EnableSwagger`配置类添加一行操作过滤注册代码即可。

c.OperationFilter();

效果图如下: ![](https://images2018.cnblogs.com/blog/534030/201806/534030-20180615154052314-1404284569.png) ## 4.7 自定义接口备注内容 由于不想将一些跟接口名无关的信息放在接口名那里,那么这个时候可以将部分业务相关的注释放在`<remarks></remarks>`标签当中

///
/// 获取后台Guid
///
///
/// 测试一些内容,不想将无用的东西放在接口名称当中

/// 换行输出一下内容
///
///
[HttpGet][ApiAuthor(Name = "jian玄冰",Status = DevStatus.Wait,Time = "2018-04-28")]
public Guid GetGuid()
{
return Guid.NewGuid();
}

效果图如下: ![](https://images2018.cnblogs.com/blog/534030/201806/534030-20180615154023207-2057293693.png) ## 4.8 设置接口开发信息 增加`ApiAuthor`特性,用于设置接口开发状态、开发人、完成时间等相关信息。

///
/// 获取后台Guid
///
///
/// 测试一些内容,不想将无用的东西放在接口名称当中

/// 换行输出一下内容
///
///
[HttpGet][AllowAnonymous]
[ApiAuthor(Name = "jian玄冰",Status = DevStatus.Wait,Time = "2018-04-28")]
public Guid GetGuid()
{
return Guid.NewGuid();
}

然后再`SwaggerConfig.cs`的`EnableSwagger`配置类添加一行启用代码即可。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfzxy.html