Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set HTTP ResponseTypes for whole class instead of for each method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading