web api routing and http post

šljaker picture šljaker · May 13, 2014 · Viewed 30.5k times · Source

I'm building an API using WEB API 2.

I have the following API controller:

[RoutePrefix("api/account")]
public class AccountController : ApiController
{
    [Route("login")]
    [HttpPost]
    public IHttpActionResult AuthenticateUser(string username, string password)
    {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        {
            return BadRequest("You must submit username and password");
        }

        if (!Membership.ValidateUser(username, password))
        {
            return BadRequest("Incorrect username or password");
        }

        FormsAuthentication.SetAuthCookie(username, true);

        return Ok();
    }
}

And jquery function:

<script>
    $(document).ready(function () {
        $("#login-form").submit(function (e) {
            e.preventDefault();

            var username = $('#username').val();
            var password = $('#password').val();

            $.ajax({
                type: 'POST',
                url: '/api/account/Login/',
                data: { username: username, password: password },
                success: function() {
                    location.reload();
                }
            });
        });
    });
</script>

When I submit the login-form, I get the following error in Google Chrome's console:

POST http://localhost:60898/api/account/Login/ 404 (Not Found)

How can I create a route that accepts HTTP POST?

Thanks!

Answer

šljaker picture šljaker · May 13, 2014

I'm sorry, I didn't see this post: WebAPI - Attribute Routing POST not working with WebAPI Cors?

I've updated my API controller like this:

[RoutePrefix("api/account")]
public class AccountController : ApiController
{
    public class LoginInfo
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    [Route("login")]
    [HttpPost]
    public IHttpActionResult AuthenticateUser(LoginInfo loginInfo)
    {
        if (string.IsNullOrEmpty(loginInfo.username) || string.IsNullOrEmpty(loginInfo.password))
        {
            return BadRequest("You must submit username and password");
        }

        if (!Membership.ValidateUser(loginInfo.username, loginInfo.password))
        {
            return BadRequest("Incorrect username or password");
        }

        FormsAuthentication.SetAuthCookie(loginInfo.username, true);

        return Ok();
    }
}

And everything works fine now.