IOperationFilter
<pre>using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace LoanCare.Services.Payment.Api.Filters; /// <summary> /// FileUpload Attribute /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class FileUploadAttribute : Attribute { } /// <summary> /// Filter for IFormFile /// </summary> public class FormFileOperationFilter : IOperationFilter { private static readonly string[] FileParameters = { "contentType", "contentDisposition", "headers", "length", "name", "fileName" }; private const string FormData = "multipart/form-data"; private const string Json = "application/json"; /// <summary> /// Apply method of IOperationFilter /// </summary> /// <param name="operation"></param> /// <param name="context"></param> public void Apply(OpenApiOperation operation, OperationFilterContext context) { //request argument null check if (context is null) { throw new ArgumentNullException(nameof(context)); } if (operation is null) { throw new ArgumentNullException(nameof(operation)); } var attr = context.MethodInfo.GetCustomAttributes(true).OfType<FileUploadAttribute>().Any(); if (!attr) { return; } var content = operation.RequestBody.Content; var jsonProperties = GetProperties(content, Json); foreach (var parameter in jsonProperties.Where(p => FileParameters.Contains(p.Key))) { jsonProperties.Remove(parameter); } if (jsonProperties.Count == 0) { content.Remove(Json); } var formDataProperties = GetProperties(content, FormData); formDataProperties.Add("file", new OpenApiSchema { Type = "file" }); } private static IDictionary<string, OpenApiSchema> GetProperties(IDictionary<string, OpenApiMediaType> contents, string mediaType) { if (!contents.ContainsKey(mediaType)) { contents.Add(mediaType, new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = new Dictionary<string, OpenApiSchema>() } }); } return contents[mediaType].Schema.Properties; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)