【问题标题】:How to display SwaggerResponse in XML instead of JSON如何在 XML 而不是 JSON 中显示 SwaggerResponse
【发布时间】:2018-10-23 11:39:17
【问题描述】:

我想在 Swagger UI 中以 XML 格式而不是 JSON 格式显示响应。我怎样才能做到这一点?这是我要改编的代码:

[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(FeedModel))]  
public async Task<IActionResult> GetCompanyPostFeed(Guid companyId)
{
    var feed = new FeedModel();

    // Some database requests

    return Content(feed, "text/xml", Encoding.UTF8);
}

【问题讨论】:

标签: c# asp.net-core swagger swagger-ui


【解决方案1】:

您可以尝试使用属性SwaggerProducesAttribute 来装饰方法,如here 所述:

[SwaggerProduces("text/xml")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(FeedModel))]  
public async Task<IActionResult> GetCompanyPostFeed(Guid companyId)

为了保持对仅链接答案的厌恶,我将在此处复制该文章的一些相关内容:

[AttributeUsage(AttributeTargets.Method)]
public class SwaggerProducesAttribute : Attribute
{
    public SwaggerProducesAttribute(params string[] contentTypes)
    {
        this.ContentTypes = contentTypes;
    }

    public IEnumerable<string> ContentTypes { get; }
}

public class ProducesOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var attribute = apiDescription.GetControllerAndActionAttributes<SwaggerProducesAttribute>().SingleOrDefault();
        if (attribute == null)
        {
            return;
        }

        operation.produces.Clear();
        operation.produces = attribute.ContentTypes.ToList();
    }
}

然后在 SwaggerConfig.cs 中,您将需要以下内容:

config
    .EnableSwagger(c =>
        {
            ...
            c.OperationFilter<ProducesOperationFilter>();
            ...
        }

【讨论】:

  • 感谢解答,但是GetControllerAndActionAttributes的方法不存在,我用的是ASP.NET Core 2.1和Swashbuckle.AspNetCore.Swagger 3.0.0
  • @frank_lbt - 这是一种扩展方法,并不复杂;您也许可以为 .NET Core 推出自己的:github.com/domaindrivendev/Swashbuckle/blob/master/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2016-01-17
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多