Search code examples
c#.net-coreswagger-uiswashbuckle

How to set the content type application/json and application/xml using Swashbuckle in swagger UI


Hi I am using Swashbuckle I want to set content type "application/json and application/xml" for request and response payload. Can anyone help me how can I set content Type according to my preferences. I have tried this code it is working for request bur not for response. [HttpPost]

    [Consumes(MediaTypeNames.Application.Json)]
    [SwaggerResponse(200,null,typeof(Logs))]
    [SwaggerResponse(400, null, typeof(Logs))]
    public async Task<IActionResult> PostAsync()

Solution

  • To configure content type for response, you can use a filters:

    public class SwaggerMediaTypesOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            foreach (var key in operation.Responses.Keys)
            {
                FilterMediaTypes(operation.Responses[key].Content);
            }
    
            if (operation.RequestBody?.Content != null)
            {
                FilterMediaTypes(operation.RequestBody.Content);
            }
        }
    
        private static void FilterMediaTypes(IDictionary<string, OpenApiMediaType> apiMediaTypes)
        {
            if (apiMediaTypes.TryGetValue(MediaTypeNames.Application.Json, out OpenApiMediaType applicationJson))
            {
                apiMediaTypes.Clear();
                apiMediaTypes.Add(MediaTypeNames.Application.Json, applicationJson);
                apiMediaTypes.Add(MediaTypeNames.Application.Xml, applicationJson);
            }
        }
    }
    

    Then,

    services.AddSwaggerGen(cfg =>
    {
      cfg.OperationFilter<SwaggerMediaTypesOperationFilter>();
      ...
    };