Christo S. Christov
Christo S. Christov

Reputation: 2309

How to return NotFound result when using web api documentation

How to indicate that a resource cannot be found and still get auto generated documentation for my Web API 2 web application?

Take for example this method definiition:

 public JsonResult<CalculatorDescription> GetParameterInfo(string parameterCaption)

If I use this definition I cannot return NotFound(), yet if I change the return type to IHttpActionResult( in order to be able to return NotFound() ) I do not get the auto-generated information for my return type.

Edit: Note that I'm using the https://msdn.microsoft.com/en-us/library/dn337124(v=vs.118).aspx JsonResult and not the MVC one ( https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.118).aspx )

Upvotes: 5

Views: 8269

Answers (1)

user47589
user47589

Reputation:

Change your return type to IHttpActionResult, and decorate your action method with the ResponseType attribute:

Use this to specify the entity type returned by an action when the declared return type is HttpResponseMessage or IHttpActionResult. The ResponseType will be read by ApiExplorer when generating ApiDescription.

Then, inside your method, return NotFound() or JsonResult<T>.

[ResponseType(typeof(CalculatorDescription))]
public IHttpActionResult GetParameterInfo(string parameterCaption)
{
    ...
    if (...) 
        return new JsonResult<CalculatorDescription>(...);
    else 
        return NotFound();        
}

Upvotes: 7

Related Questions