Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning 400 rather than 404 from ASP.NET MVC Web API

I have created the hello world of ASP.NET MVC web API projects using VS2012:

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

Issuing a get request to that controller returns some XML of the data with status 200. All good so far.

When I remove that method, like this:

public class ValuesController : ApiController
{
    // GET api/values
    //public IEnumerable<string> Get()
    //{
    //    return new string[] { "value1", "value2" };
    //}

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

I then get a 404 not found. What I want is a 400 bad request, because an ID must be provided. How can I achieve this?

like image 717
sennett Avatar asked Jan 07 '13 01:01

sennett


1 Answers

You don't need to keep the Get() method just to throw an error. Change the signature of your Get by ID method to:

public string Get(int? id = null)
{
    if (id == null) throw new HttpResponseException(HttpStatusCode.BadRequest);
    return "value";
}
like image 101
Filip W Avatar answered Nov 29 '22 04:11

Filip W