相关疑难解决方法(0)

限制ASP.NET Core Controller操作中接受的媒体类型

我有一个同时生成JSON和XML响应的ASP.NET Core Service。但是,我只想限制一个动作接受的媒体类型,因此Swagger只能将application / json列为有效的响应内容类型。如何在ASP.Net Core中实现此目标?

请考虑我正在使用ASP.Net Core(ASP.NET MVC 6),而不是ASP.NET WebAPI。

在此处输入图片说明

更新

好的,所以我将答案添加为同一问题的一部分。感谢@Helen,我能够在ASP.Net Core(ASP.Net MVC 6)中添加所需的类来实现此目的。答案基于此答案,但已修改为使用ASP.NET Core类。

步骤1.创建一个自定义操作过滤器属性,以便管道对禁止的内容类型做出反应:

/// <summary>
/// SwaggerResponseContentTypeAttribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerResponseContentTypeAttribute : ActionFilterAttribute
{
    /// <summary>
    /// SwaggerResponseContentTypeAttribute
    /// </summary>
    /// <param name="responseType"></param>
    public SwaggerResponseContentTypeAttribute(string responseType)
    {
        ResponseType = responseType;
    }
    /// <summary>
    /// Response Content Type
    /// </summary>
    public string ResponseType { get; private set; }

    /// <summary>
    /// Remove all other Response Content Types
    /// …
Run Code Online (Sandbox Code Playgroud)

asp.net media-type swagger-ui asp.net-core

6
推荐指数
2
解决办法
2963
查看次数

标签 统计

asp.net ×1

asp.net-core ×1

media-type ×1

swagger-ui ×1