asp.netasp.net-web-apiasp.net-web-api2asp.net-web-api-routing

When and how to use [ResponseType(typeof(...))] correctly?


I am working on a project and I have a basic controller with Get(int id), GetElements(), UpdateElement(int id, Element element), AddElement(Element element) and DeleteElement(int id). Every method use [Route] and [Get]... annotations and returns an IHttpActionResult.

I am confused about [ResponseType(typeof(...))]. What is it for? When and how to use it correctly?

Should I write something like this? [ResponseType(typeof(IEnumerable<Element>))] for GetElements()?

Thanks!


Solution

  • The [ResponseType()] attribute is helpful for creating RESTful Web APIs and also when autogenerating documentation via Swagger / Swashbuckle.

    For instance, an approach to returning an item based on an id could be written like this

    public YourClass Get(int id)
    {
        var item = repo.GetById(id);
        return item;
    }
    

    However, if that item is not found, it will return null, rather than a 404.

    So it could be better written as

    [ResponseType(typeof(YourClass))]
    public IHttpActionResult Get(int id)
    {
        var item = repo.GetById(id);
        if (item != null)
        {
            return this.Ok(item);
        }
    
        return this.NotFound();
    }
    

    See more uses of this here http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing

    See also customizing Swashbuckle and how it ResponseType attributes can be used to determine documentation https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/