简体   繁体   English

使用ASP.NET MVC进行jQuery Forms身份验证

[英]jQuery Forms Authentication with ASP.NET MVC

Is it possible to use a jQuery ajax call to perform Forms Authentication with ASP.NET MVC? 是否可以使用jQuery ajax调用来执行ASP.NET MVC的表单身份验证? I've been unable to find any such examples. 我一直都找不到这样的例子。

More specifically, how do I set the auth cookie on the page (without a redirect) so I can make successive authenticated ajax requests? 更具体地说,如何在页面上设置auth cookie(没有重定向),以便我可以进行连续的经过身份验证的ajax请求?

Yes, it's possible. 是的,这是可能的。 Just submit the login-form using the method described here by mike bosch and return a json datastructure with the returnUrl if any. 只需使用mike bosch所述的方法提交登录表单,并返回带有returnUrl的json数据结构(如果有的话)。

I have created a lightweight LoginResultDTO class that i return as json: 我创建了一个轻量级的LoginResultDTO类,我以json的形式返回:

public class LoginResultDTO
{
  public bool Success {get;set;}
  public string Message {get;set;}
  public string ReturnUrl {get;set;}
}

Here's a script block from my LogOn view: 这是我的LogOn视图中的一个脚本块:

<script type="text/javascript">
        $(document).ready(function() {
            var form = $($("form")[0]);
            form.submit(function() {
                var data = form.serialize();
                $.post(form.attr("action"), data, function(result, status) {
                    if (result.Success && result.ReturnUrl) {
                            location.href = result.ReturnUrl;
                    } else {
                        alert(result.Message);
                    }
                }, "json");
                return false;
            });
        });
</script>

This will ajax wrap the logon form. 这将是ajax包装登录表单。 Note that this is the simplest implementation of the javascript code possible but it's a place to start. 请注意,这是javascript代码最简单的实现,但它是一个开始的地方。

Then I have modified my LogOn action in the AccountController and in the relevant places put something like this: 然后我在AccountController中修改了我的LogOn动作,在相关的地方放了这样的东西:

if(Request.IsAjaxRequest())
{
  return Json(new LoginResultDTO{Success=true,Message="Successfully logged in"});
}else
{
  return View();
}

So this is an ultralight but rather complete version of how jquery authentication could be done in asp.net mvc. 所以这是一个超级但相当完整的版本,可以在asp.net mvc中完成jquery身份验证。

Steve Reynolds has a good article on how to do some of this. 史蒂夫雷诺兹有一篇关于如何做到这一点的好文章。

Link to article 链接到文章

Take a look at xVal . 看看xVal It can use any client-side validation library but uses jQuery Valiation by default. 它可以使用任何客户端验证库,但默认情况下使用jQuery Valiation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM