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?
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With