Home > Net >  Set HTTP ResponseTypes for whole class instead of for each method
Set HTTP ResponseTypes for whole class instead of for each method

Time:12-02

In an ASP.NET MVC project, we have several endpoint methods where some of the tags are set for all methods, such as the ProducesResponseType((int)HttpStatusCode.OK) tag.

Is there a way to set some response for all methods in the class?

As you can see four lines of code are used for only the status codes

/// <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()

CodePudding user response:

You can apply such ProducesResponseType attribute on your controller class, since this attribute can be applied on both a method or a class as specified by its 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
{
}

To take this even further, you can go for a convention based approach, but that looks like more than you are asking for.

  • Related