Search code examples
c#asp.net-web-api2asp.net-mvc-routing

What's wrong with my routes


I have the following routes declared in the webApiConfig.

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

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

Here are the route attributes on the controller:

[Route("users")]
public IHttpActionResult Get()


[Route("users/{id}")]
public IHttpActionResult Get(int id)

[AllowAnonymous]
[HttpPost]
[Route("users/validate")]
public IHttpActionResult Validate(string email)

When I make a call to:
~/api/users -- it works
~/api/users/1 -- it works
~/api/users/validate -- fails... trys to go into the api/users/1 but fails because of the Post verb.

How do I set up the routes so that I can validate a user in the user controller?


Solution

  • You do not need to register Custom Route, as you already have Attribute Route.

    Remove DefaultApiWithAction route from your code. Instead, you will need RoutePrefix.

    [RoutePrefix("api/users")]
    public class UsersController : ApiController
    {
        public IHttpActionResult Get()
        {
            return Ok(new [] {"value1", "value2"});
        }
    
        public IHttpActionResult Get(int id)
        {
            return Ok(id);
        }
    
        [HttpPost]
        [Route("validate")]
        public IHttpActionResult Validate([FromBody]string email)
        {
            return Ok(email);
        }
    }
    

    How to Test HttpPost

    Install Postman in Chrome browser. You can also use Fiddler or some other tools.

    1. Select POST and enter URL http://localhost:XXXXX/api/users/validate
    2. Select application/json as content type
    3. Enter content "johndoe@example.com"
    4. After clicking Send, you should see the result

    enter image description here

    API Break Point

    enter image description here