I am developing an ASP.Net MVC application. In my project I am providing REST API for mobile devices. But I am having a problem with configuring route for URLs of my rest API in Web Api. I am using Web Api 2 and MVC 5. My problem is routes having conflict. Request cannot choose the correct route even I configured it clearly.
I have AccountController like this.
[RoutePrefix("v1")]
public class AccountController : ApiController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpPost]
public async Task<IHttpActionResult> Register(RegisterBM model)
{
}
[HttpPost]
public IHttpActionResult Login(LoginBM model)
{
}
}
I configured routes in WebApiConfig like this
config.Routes.MapHttpRoute(
name: "",
routeTemplate: "api/v1/account/register",
defaults: new { controller = "Account", action = "Register" ,model = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "",
routeTemplate: "api/v1/account/login",
defaults: new { controller = "Account", action = "Login", model = RouteParameter.Optional }
);
These are my model classes
public class LoginBM
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
public class RegisterBM
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
[MaxLength(70)]
[UniqueAccountEmail(ErrorMessage = "Email is alreay taken")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
This is error I get when I make request to http://localhost:50489/api/account/login
What is wrong with my route configuration? How can I fix that?
The URL you are testing http://localhost:50489/api/account/login
does not match the routeTemplate
of the route you have provided api/v1/account/login
, namely you are missing v1
from the URL. Your test is apparently reaching another route, which is causing this exception.
Since Web API and MVC are separate frameworks, each has their own controllers. URLs must be unique for the application, but route values are not shared between them. So you can use the same set of route values in both frameworks (same names for controllers and actions) provided you use unique URLs across them both. Generally, this is done by prefixing the Web Api URL with /api
(which you have already done). But if you put a version in the routeTemplate
, you must also use it in the actual URL or you will not reach the controller action.