Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api 2: NotFound() with content?

I have the following resource used to return specific company information:

[HttpGet]
[Route("{companyId:Guid}")]
public IHttpActionResult Get(Guid companyId)
{
    var company = CompanyRepository.Find(companyId);

    if (company == null)
    {
        return NotFound();
    }
    else
    {
        var responseModel = new CompanyResponseModel()
        {
            CompanyId = company.Id,
            Name = company.Name
        };

        return Ok(responseModel);
    }
}

Why can we not include content into the NotFound() call?

For example, I would like to include an error response model with a message "Company ID does not exist".

Is this perhaps against RESTful design?

like image 293
Dave New Avatar asked Nov 17 '14 09:11

Dave New


People also ask

What happens if the return type is void in web API?

If the return type is void, Web API simply returns an empty HTTP response with status code 204 (No Content).

How to handle HTTP GET request in a web API controller?

In this section we will implement Get action methods in our Web API controller class that will handle HTTP GET requests. As per the Web API naming convention, action method that starts with a word "Get" will handle HTTP GET request. We can either name it only Get or with any suffix.

Why multiple actions found error occurs in HTTP GET request?

The above web API example will compile without an error but when you execute HTTP GET request then it will respond with the following multiple actions found error. This is because you cannot have multiple action methods with same number of parameters with same type. Both action methods above do not include any parameters.

What can a web API controller action return?

A Web API controller action can return any of the following: 1 void 2 HttpResponseMessage 3 IHttpActionResult 4 Some other type More ...


1 Answers

According to RFC2616 Section 10 the 404 does not return any information about the resource itself. But if you want to use the 404 you can use this instead:

return Content(HttpStatusCode.NotFound, "Your Content/Message");
like image 87
Stefan Ossendorf Avatar answered Oct 25 '22 05:10

Stefan Ossendorf