Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Created August 26, 2018 06:04
Show Gist options
  • Select an option

  • Save jenyayel/253b2a5254bc9e4163ca20b3896b394a to your computer and use it in GitHub Desktop.

Select an option

Save jenyayel/253b2a5254bc9e4163ca20b3896b394a to your computer and use it in GitHub Desktop.
Replace IFormFile with parameter for uploading file via Swagger
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Reflection;
namespace Api.Filters
{
public class FileOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
foreach (var actionParam in context.ApiDescription.ActionDescriptor.Parameters)
{
var paramName =
actionParam.ParameterType == typeof(IFormFile) ?
actionParam.Name : // passed directly as param in method of action
actionParam.ParameterType // passed as model with property of IFormFile
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(p => p.PropertyType == typeof(IFormFile))
?.Name;
if (paramName == null) continue;
var operationParam = operation.Parameters
.FirstOrDefault(p => p.Name.Equals(paramName, StringComparison.OrdinalIgnoreCase));
if (operationParam == null) continue;
// remove parameter
operation.Parameters.Remove(operationParam);
// insert modified
var fileParam = new NonBodyParameter
{
Type = "file",
In = "formData",
Description = operationParam.Description,
Name = operationParam.Name,
Required = operationParam.Required,
};
operation.Parameters.Add(fileParam);
operation.Consumes.Add("multipart/form-data");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment