Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Net Core API: Purpose of ProducesResponseType

People also ask

What is the use of ProducesResponseType?

This attribute produces more descriptive response details for web API help pages generated by tools like Swagger. [ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action.

What is difference between ActionResult and IActionResult?

IActionResult is an interface and ActionResult is an implementation of that interface. ActionResults is an abstract class and action results like ViewResult, PartialViewResult, JsonResult, etc., derive from ActionResult.

What is return type in Web API?

A Web API controller action can return any of the following: void. HttpResponseMessage. IHttpActionResult.


I think it can come handy for non-success (200) return codes. Say if one of the failure status codes returns a model that describes the problem, you can specify that the status code in that case produces something different than the success case. You can read more about that and find examples here: https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.2


It's for producing Open API metadata for API exploration/visualization tools such as Swagger (https://swagger.io/), to indicate in the documentation what the controller may return.


Although the correct answer is already submitted, I would like to provide an example. Assume you have added the Swashbuckle.AspNetCore package to your project, and have used it in Startup.Configure(...) like this:

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web Service API V1");
    options.RoutePrefix = "api/docs";  

});

Having a test controller action endpoint like this:

[HttpGet]        
public ActionResult GetAllItems()
{
    if ((new Random()).Next() % 2 == 0)
    {
        return Ok(new string[] { "value1", "value2" });
    }
    else
    {
        return Problem(detail: "No Items Found, Don't Try Again!");
    }
}

Will result in a swagger UI card/section like this (Run the project and navigate to /api/docs/index.html):

enter image description here

As you can see, there is no 'metadata' provided for the endpoint.

Now, update the endpoint to this:

[HttpGet]
[ProducesResponseType(typeof(IEnumerable<string>), 200)]
[ProducesResponseType(404)]
public ActionResult GetAllItems()
{
    if ((new Random()).Next() % 2 == 0)
    {
        return Ok(new string[] { "value1", "value2" });
    }
    else
    {
        return Problem(detail: "No Items Found, Don't Try Again!");
    }
}

This won't change the behavior of your endpoint at all, but now the swagger page looks like this:

enter image description here

This is much nicer, because now the client can see what are the possible response status codes, and for each response status, what is the type/structure of the returned data. Please note that although I have not defined the return type for 404, but ASP.NET Core (I'm using .NET 5) is smart enough to set the return type to ProblemDetails.

If this is the path you want to take, it's a good idea to add the Web API Analyzer to your project, to receive some useful warnings.

p.s. I would also like to use options.DisplayOperationId(); in app.UseSwaggerUI(...) configuration. By doing so, swagger UI will display the name of the actual .NET method that is mapped to each endpoint. For example, the above endpoint is a GET to /api/sample but the actual .NET method is called GetAllItems()