Reputation: 7555
Below is WebAPI.
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
[Route("{id:int:min(1)}/")]
public HttpResponseMessage Get(int id)
{
//my stuff
}
}
If I pass any value less than 1 (say 0 or -1). It returns response body as NUll with HttpStatusCode = 200
The expected response is: HttpStatus Code = 404.
However, if I modify my route as below.
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
[Route("detail/{id:int:min(1)}/")]
public HttpResponseMessage Get(int id)
{
//my stuff
}
}
Now if I pass the value less than 1, I get the expected response i.e., 404.
http://localhost:8080/api/customer/detail/-1 returns - 404.(Desired response).
http://localhost:8080/api/customer/-1 returns - Null.(Not correct).
What is causing this & how do I fix this??
Any help/suggestion highly appreciated.
Upvotes: 4
Views: 2251
Reputation: 1809
You should remove
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
from your WebApi.Config routing. What happens is the route /api/customers/-1 fails the attribute route because it doesn't meet the constraint. This however does not halt it from looking for other matching routes.
If attribute routing was all you were using you would get a 404, however, after this route fails the framework continues looking for a viable route which it finds in your "DefaultApi" route. So it uses customers for the {controller} and -1 for the {id} and passes this to your Get method.
Upvotes: 0