web api routing and http post

本文关键字:http post and routing api web | 更新日期: 2023-09-27 18:03:14

我正在使用WEB API 2构建一个API。

我有以下API控制器:

[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();
    }
}

和jquery函数:

<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>

当我提交登录表单时,我在Google Chrome的控制台得到以下错误:

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

如何创建一个接受HTTP POST的路由?

谢谢!

web api routing and http post

我很抱歉,我没有看到这个帖子:WebAPI -属性路由post不与WebAPI Cors工作?

我已经更新了我的API控制器如下:

[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();
    }
}

现在一切都好了