登录后如何返回上一个URL? (AJAX)

时间:2015-10-29 03:58:17

标签: c# asp.net-mvc asp.net-identity authorize-attribute form-authentication

所以我有一个MVC5 Web应用程序(它带有ASP.Identity框架),我有这个自定义Authorize属性。

public class FrontEndAuthorize : AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        dynamic user = (ClaimsPrincipal)httpContext.User;

        if (user.Identity.IsAuthenticated) {
            return true;
        }

        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext context)
    {
        if (context.HttpContext.Request.IsAjaxRequest()) {
            dynamic urlHelper = new UrlHelper(context.RequestContext);
            context.HttpContext.Response.TrySkipIisCustomErrors = true;
            context.HttpContext.Response.StatusCode = 403;

            context.Result = new JsonResult {
                Data = new {
                    Error = "NotAuthorized",
                    LogOnUrl = urlHelper.Action("LogIn", "Account")
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        } else {
            base.HandleUnauthorizedRequest(context);
        }
    }
}

我对ajax方法有一些问题。例如,如果我有文章页面warheat1990.com/articles/batman-arkham-knight-review,并带有提交评论的按钮。

[HttpPost]
[FrontEndAuthorize]
public ActionResult SubmitComment(string comment)
{
    //code here
    return Content("success");
}

当用户单击“提交注释”按钮时,我有一个脚本来调用该方法。

$.ajax({
    url: '/Articles/SubmitComment/'
    type: 'POST'
    //rest of code here
})

当用户首先单击没有LogIn的“提交注释”按钮时,用户将被重定向到“登录”页面,但是在LogIn成功时,用户将被带回主页,即warheat1990.com而不是warheat1990.com/articles/batman-arkham-knight-review

这是由ajax调用SubmitComment方法引起的。所以我的问题是我应该怎么做才能在ajax调用上将用户重定向到上一页?

3 个答案:

答案 0 :(得分:3)

基本的想法是你的HandleUnauthorizedRequest方法需要提供一个"返回"处理登录的页面/控制器的参数。而不是将您的用户发送到登录页面:

LogOnUrl = urlHelper.Action("LogIn", "Account")

您将提供额外的returnUrl查询参数:

// for your ajax
LogOnUrl = urlHelper.Action("LogIn", "Account", new { returnUrl = context.HttpContext.Request.RawUrl })

// for your non-ajax:
context.Result = new RedirectToRouteResult(
                new System.Web.Routing.RouteValueDictionary
                    {                     
                            { "controller", "Account" },
                            { "action", "Login" },
                            { "returnUrl", context.HttpContext.Request.RawUrl }
                    });

用户将登陆以下页面:

warheat1990.com/login?returnUrl=warheat1990.com%2Farticles%2Fbatman-arkham-knight-review

如果登录成功,那么您将解析查询参数returnUrl值的请求(如果存在),并将用户重定向到该位置。

答案 1 :(得分:1)

您可以获得下面的来电网址

if (context.HttpContext.Request.IsAjaxRequest())
            {
                UrlHelper urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.TrySkipIisCustomErrors = true;
                context.HttpContext.Response.StatusCode = 403;

                /* Get return url */
                var returnUrl = context.RequestContext.HttpContext.Request.Url.PathAndQuery;
                context.Result = new JsonResult
                    {
                        Data = new
                            {
                                Error = "NotAuthorized",
                                LogOnUrl = urlHelper.Action("LogIn", "Account", new {returnUrl})
                            },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
            }
            else
            {
                base.HandleUnauthorizedRequest(context);
            }

并在帐户控制器和索引操作中重定向到该网址

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
           /* Together with some other code */
           return RedirectToLocal(returnUrl);

        }

答案 2 :(得分:0)

您可以通过Request.UrlReferrer或Request.ServerVariables [“http_referer”]获取先前的请求。

然后,一旦完成登录过程,您就可以重定向到此URL