Hristo Hristo - 25 days ago 9
C# Question

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 )

Amy Amy
Answer

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