Route options not working in WebApi

Below is the 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 (e.g. 0 or -1). It returns the response body as null withHttpStatusCode = 200

Expected answer: HttpStatus Code = 404.

However, if I change my route as shown 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 a 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 causes this and how can I fix it?

Any help / suggestion was greatly appreciated.

+4
source share
1 answer

You must remove

       config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional });

from your routing WebApi.Config. It happens that the route / api / customers / -1 does not go through the attribute route because it does not meet the restrictions. However, this does not prevent him from looking for other suitable routes.

, , 404, , , , "DefaultApi". {controller} -1 {id} Get.

0

Source: https://habr.com/ru/post/1673991/


All Articles