【问题标题】:Authorize attribute and jquery AJAX in asp.net MVC在 asp.net MVC 中授权属性和 jquery AJAX
【发布时间】:2011-03-10 11:00:23
【问题描述】:

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

[Authorize]
public ActionResult Creat()
{
....
}

如果用户未登录,则操作将登录页面返回到 jquery 的 ajax 函数,并显示在同一页面上,但我想将用户重定向到登录页面。 有什么解决办法吗?

【问题讨论】:

    标签: asp.net-mvc ajax authorize


    【解决方案1】:

    工作示例: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);
                }
            }
        }
    }
    

    Javascript:

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

    在控制器中使用属性:

        [AjaxAuthorize]
        public ActionResult Secret()
        {
            return PartialView();
        }
    

    做一些 ajax:

    @Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })
    
    <div id="secretArea"></div>
    

    【讨论】:

    • 太棒了罗尼!当解决方案有效时,我喜欢它! Ghooti 需要标记这个答案...
    • 我使用formsauthentication重定向,必须输入这行代码来防止重定向和返回正确的http状态... filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
    • 操作上的 [AjaxAuthorize] 属性会覆盖整个控制器上的 [Authorize] 属性吗?
    • @Odys:不,这不适用于 401 状态代码。 ASP.net 管道在启动之前会干扰 401。坚持使用 403。
    • @DeepakMurali 好吧,该死的。我来自 200 年代是一件好事。
    【解决方案2】:

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

    如果您想在重定向时保留页面 url。

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

    【讨论】:

    • 更简单的解决方案imo:returnUrl = context.HttpContext.Request.UrlReferrer.LocalPath for routeValues of urlHelper.Action
    【解决方案3】:

    作为 Ronnie Overby 回答的另一个扩展。

    他的解决方案不适用于webapi,但这很好,因为你可以使用普通的Authorize 属性,然后在 ajaxError 函数中处理 401 状态,如下所示。

        $(document).ajaxError(function (e, xhr) {
        //ajax error event handler that looks for either a 401 (regular authorized) or 403 (AjaxAuthorized custom actionfilter). 
        if (xhr.status == 403 ||xhr.status == 401) {
           //code here
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      相关资源
      最近更新 更多