Last active
January 15, 2018 13:48
-
-
Save matteus6007/668d4b9241303650530228150a99096d to your computer and use it in GitHub Desktop.
BaseResponse wrapper for swagger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Web.Http.Description; | |
using Swashbuckle.Swagger; | |
using System.Linq; | |
using System; | |
using System.Collections.Generic; | |
namespace Swagger.Filters | |
{ | |
public class GenericWrapper<T> | |
{ | |
public T Data { get; set; } | |
public List<string> Errors { get; set; } | |
} | |
/// <summary> | |
/// Swagger filter for wrapping controller responses with a <see cref="GenericWrapper<T>" /> | |
/// </summary> | |
public class BaseResponseTypeFilter : IOperationFilter | |
{ | |
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) | |
{ | |
foreach (var response in operation.responses) | |
{ | |
if (string.IsNullOrEmpty(response.Value.schema.@ref)) continue; | |
var schemaRefType = response.Value.schema.@ref.Split('/')?.Last(); | |
var responseType = AppDomain.CurrentDomain.GetAssemblies() | |
.SelectMany(a => a.GetTypes()) | |
.Where(t => t.FullName.Equals(schemaRefType, StringComparison.InvariantCultureIgnoreCase)) | |
.FirstOrDefault(); | |
if (responseType == null) continue; | |
var genericType = typeof(GenericWrapper<object>); | |
var baseResponseType = Type.GetType($"{genericType.Namespace}.{genericType.Name}[[{responseType.AssemblyQualifiedName}]], {genericType.Assembly.FullName}"); | |
var baseHttpResponseSchema = schemaRegistry.GetOrRegister(baseResponseType); | |
response.Value.schema.@ref = baseHttpResponseSchema.@ref; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment