Skip to content

Instantly share code, notes, and snippets.

@matteus6007
Last active January 15, 2018 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteus6007/668d4b9241303650530228150a99096d to your computer and use it in GitHub Desktop.
Save matteus6007/668d4b9241303650530228150a99096d to your computer and use it in GitHub Desktop.
BaseResponse wrapper for swagger
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