【问题标题】:Set HTTP ResponseTypes for whole class instead of for each method为整个类而不是为每个方法设置 HTTP ResponseTypes
【发布时间】:2022-01-08 22:24:45
【问题描述】:

在 ASP.NET MVC 项目中,我们有几个端点方法,其中为所有方法设置了一些标记,例如 ProducesResponseType((int)HttpStatusCode.OK) 标记。

有没有办法为类中的所有方法设置一些响应?

如您所见,四行代码仅用于状态代码

/// <summary> A summary describing the endpoint</summary>
[HttpPost("RenameSomething/", Name = "Rename[controller]")]
[Produces("application/json")]
[ProducesResponseType((int)HttpStatusCode.OK),
 ProducesResponseType((int)HttpStatusCode.NotFound),
 ProducesResponseType((int)HttpStatusCode.BadRequest),
 ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public ActionResult RenameSomething()

【问题讨论】:

    标签: c# asp.net-mvc api swagger


    【解决方案1】:

    您可以在控制器类上应用此类ProducesResponseType 属性, 因为这个属性既可以应用于方法也可以应用于AttributeUsage指定的类。

    [System.AttributeUsage(  
        System.AttributeTargets.Class |  
        System.AttributeTargets.Method,  
        AllowMultiple=true, Inherited=true
        )]
    public class ProducesResponseTypeAttribute : Attribute
    

    [ProducesResponseType((int)HttpStatusCode.OK),
        ProducesResponseType((int)HttpStatusCode.NotFound),
        ProducesResponseType((int)HttpStatusCode.BadRequest),
        ProducesResponseType((int)HttpStatusCode.InternalServerError)
        ]
    public class MyController : Controller
    {
    }
    

    为了更进一步,您可以联系convention based approach,但这看起来比您要求的要多。

    【讨论】:

    • 谢谢,太好了,我已经在实施了。假设方法标记[ProducesResponseType(typeof(IEnumerable&lt;SomethingDto&gt;), (int)HttpStatusCode.OK) 将覆盖类标记[ProducesResponseType((int)HttpStatusCode.OK)] 是否安全?
    • @jonadv 据我所知/记得,类级别的属性与方法级别的属性相加。
    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多