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

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

问题描述

我已经使用jQuery的AJAX功能提交表单。 则用户必须先登录否则,他们必须重定向到登录page.I已经使用授权()属性了。

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?

推荐答案

工作例如:<一href="https://github.com/ronnieoverby/mvc-ajax-auth">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:

Do some ajax:

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

<div id="secretArea"></div>

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

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