How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?

11,498

Solution 1

references:

ASP.NET Core APIs in the fast lane with Swagger and Autorest

Adding swagger in ASP.NET Core Web API

ASP.NET Core 1.0 MVC API documentation using Swashbuckle Swagger

For output definition, just add the [Produces] and [SwaggerResponse] attributes describing the Type returned, like this:

[HttpGet]
[Produces(typeof(Employee))]
[SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(Employee))]
public async Task<IActionResult> LoadEmployee(string id) {
    var employee = await repository.GetById(id);
    if(employee == null) {
        return NotFound();
    }
    return Ok(employee);
}

Solution 2

You can just use StatusCodeResult StatusCode(...) to return status code and a message/object.

public async Task<ObjectResult> LoadEmployee(string id)
{
    var employee = await repository.GetById(id);
    if(employee == null) {
        return NotFound();
    }

    return StatusCode((int)HttpStatusCode.Ok, employee);
}

Solution 3

ProducesResponseType attribute is supported by Swagger and is a MVC Web API Core attribute, not Swagger. Does the same as SwaggerResponse.

Share:
11,498
Erick T
Author by

Erick T

Updated on June 27, 2022

Comments

  • Erick T
    Erick T almost 2 years

    I have an ASP.NET Core Web API site, with Swagger generation and UI enabled. In order for Swagger to work (at least work automatically), the return value from the controller method must be typed. For example,

    public async Task<Employee> LoadEmployee(string id)
    

    However, I need to return custom HTTP status codes and content from this action. All the examples I've seen use the StatusCode method, or return some other object. The problem with this is then Swagger doesn't know what the return type of the action is, and so can't generate the API spec.

    Is there some way (Exception, methods on controller, etc) to return the custom code/content, while keeping the signature? I've seen solutions using custom middleware, but it seems like a common enough scenario that there should be something built it.