4

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.

3 Answers 3

9

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

not working in Api, has just 1 parameter for status and cannot pass employee
3

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);
}

1 Comment

Thanks. I was hoping to avoid swagger specific code (as opposed to the API being mainly self documented) but this works.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.