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?
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);
}
}
Install Postman in Chrome browser. You can also use Fiddler or some other tools.
http://localhost:XXXXX/api/users/validate
application/json
as content type"johndoe@example.com"