在asp.net MVC中授权属性和jquery AJAX

Gho*_*ngi 34 ajax asp.net-mvc authorize

我使用jquery ajax函数提交表单.用户必须登录,否则他们必须重定向到登录页面.我已经使用了Authorize()属性.

[Authorize]
public ActionResult Creat()
{
....
}
Run Code Online (Sandbox Code Playgroud)

如果用户没有登录操作返回登录页面到jquery的ajax函数,它会显示在同一页面上,但我想将用户重定向到登录页面.有什么解决方案吗?

Ron*_*rby 87

工作示例:https://github.com/ronnieoverby/mvc-ajax-auth

重要部分:

AjaxAuthorizeAttribute:

using System.Web.Mvc;

namespace MvcApplication1
{
    public class AjaxAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NotAuthorized",
                        LogOnUrl = urlHelper.Action("LogOn", "Account")
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(context);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

    $(function () {
        $(document).ajaxError(function (e, xhr) {
            if (xhr.status == 403) {
                var response = $.parseJSON(xhr.responseText);
                window.location = response.LogOnUrl;
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

在控制器中使用该属性:

    [AjaxAuthorize]
    public ActionResult Secret()
    {
        return PartialView();
    }
Run Code Online (Sandbox Code Playgroud)

做一些ajax:

@Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })

<div id="secretArea"></div>
Run Code Online (Sandbox Code Playgroud)

  • 罗尼非常棒!当解决方案正常运行时,我喜欢它!Ghooti需要标记这个答案...... (3认同)
  • 获得铜牌 (3认同)
  • 我正在使用formsauthentication重定向,并且必须输入这行代码以防止重定向并返回正确的http状态... filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; (3认同)

Mud*_*auf 8

只是#Ronnie答案的一个方便的补充

如果你想保持页面网址重定向.

 var pathname = window.location.pathname;
        if (xhr.status == 403) {
                var response = $.parseJSON(xhr.responseText);
                window.location = response.LogOnUrl + '?ReturnUrl=' + pathname;
            }
Run Code Online (Sandbox Code Playgroud)