Search code examples
c#asp.net-mvcasp.net-web-apiasp.net-web-api-routing

WebApi returns Http error 500, probably a routing issue


I have the following Web Api class:

public class BizAuthController : ApiController
{
    [HttpPost]
    public __BizAuthModel Register([FromBody] __BizAuthModel authInfo)
    {
        if (ModelState.IsValid)
        {
          //... do whatever
        }
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    [HttpPost]
    public __BizAuthModel Login([FromBody] __BizAuthModel authInfo)
    {
        if (ModelState.IsValid)
        {
          //... do whatever
        }
        throw new HttpResponseException(HttpStatusCode.Forbidden);
    }

}

This is my WebApiConfig (standard, I didn't touch it):

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Now, if I delete the "Login" method the "Register" can be called and works fine. If I keep the "Login" method then calling the "Register" returns Http Error 500. Why? and how can I fix this?


Solution

  • framework does not know which action to use on POST. Those two action match the default routeTemplate.

    Update the convention-based route to api/{controller}/{action}/{id} and call the actions by name rather than by only HttpMethod. ie: POST api/BizAuth/Register and POST api/BizAuth/Login

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
        }
    }