Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

.net - jQuery Forms Authentication with ASP.NET MVC

Is it possible to use a jQuery ajax call to perform Forms Authentication with 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

I have created a lightweight LoginResultDTO class that i return as 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:

<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. Note that this is the simplest implementation of the javascript code possible but it's a place to start.

Then I have modified my LogOn action in the AccountController and in the relevant places put something like this:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...