在asp.net MVC中授权属性和jquery AJAX [英] Authorize attribute and jquery AJAX in asp.net MVC

查看:32
本文介绍了在asp.net MVC中授权属性和jquery AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used jquery ajax function to submit a form. The users have to be logged in else they must redirect to a login page.I have used Authorize() attribute for it.

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

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

If the user is not login the action return login page to jquery's ajax functions and it is displayed on the same page but I want to redirect the user to login page. Is there any solution?

推荐答案

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

重要部分:

AjaxAuthorizeAttribute:

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:

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>

这篇关于在asp.net MVC中授权属性和jquery AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆