Cody Jones
Cody Jones

Reputation: 434

How to use POST in ApiController

I have searched for at least an hour and a half now and I'm not any closer to learning how to use POST methods in my ApiController. I need an effective way of using post to create a login system that will search my database based on the username/password combination and create a JSON object that I can send back to my web page. Any resources on using post? I've tried to acomplish this with get but I can use any variables more than 'ID'

public IHttpActionResult GetLogin(string id)
        {
            //Query Database for Unique username.

            if (id == "mager1794")
            {

                //Create Login class with username, and password details.
                return Ok( new Models.Login() { id = 1, userName = "mager1794", passWord = "*******" });
            }


            return Ok(-1);
        }

This is what I have for my Get method but I'm just not having any luck creating a POST version of this.

Upvotes: 0

Views: 58

Answers (1)

šljaker
šljaker

Reputation: 7374

Maybe something like this:

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

        [Required]
        public string Password { get; set; }
    }

    [Route("login")]
    [HttpPost]
    public IHttpActionResult AuthenticateUser(LoginInfo loginInfo)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

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

        FormsAuthentication.SetAuthCookie(loginInfo.Username, true);

        return Ok();
    }
}

Client side:

<form action="#" id="login-form">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username"/>

    <label for="password">Password:</label>
    <input type="password" name="password" id="password"/>
    <div><input type="submit"/></div>
</form>

<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 () {
                   // refresh the page if username and password are correct
                   location.reload();
               }
           });
       });
   });
</script>

Upvotes: 1

Related Questions