控制器中Ajax Action方法上的Authorize属性 [英] Authorize attribute on Ajax Action methods in controller

查看:170
本文介绍了控制器中Ajax Action方法上的Authorize属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的MVC3应用程序中授权ajax操作方法.当用户会话过期并且要求执行ajax操作方法时,会发生此问题. asp.net身份验证系统发送302重定向,而不是发送401,这对于非ajax请求似乎是合理的.但是有了Ajax,一切很快就搞砸了.因此,我决定采用

I was trying to authorize ajax action methods in my MVC3 application. The problem occurs when the user session expires and an ajax action method is asked to execute. The asp.net Authentication system sends 302 redirect instead of sending 401 which seems logical for non-ajax requests. But with Ajax it all gets messed up quickly. So I decided to follow the approach suggested at ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active . Basically, at the end of request we check whether the request is an ajax request and there is a redirect (302 response). If it is then we replace the response code from 302 to 401. Accordingly in the javascript we check for 401 and perform redirection from there. Here is the basic code that I have put up

在Global.asax.cs

In Global.asax.cs

    protected void Application_EndRequest() {
        var context = new HttpContextWrapper(Context);
        // If we're an ajax request, and doing a 302, then we actually need to do a 401
        if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest()) {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }

在JQuery全局错误处理程序中(包含在asp.net mvc主页中:_Layout.cshtml)

In JQuery global error handler (included in asp.net mvc master page : _Layout.cshtml)

$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
    if (jqXHR.status == 401) {
        window.location.replace(loginUrl);
    }
});

我刚刚快速测试了此代码,它似乎工作正常.此代码是否有任何潜在的问题.就asp.net mvc和jquery而言,我是一个相对较新的程序员,所以我认为在实际实现代码之前,我会征询其他意见.

I have just quickly tested this code and it seems to work fine. Is there any potential problem with this code. I am a relatively novice programmer as far as asp.net mvc and jquery are concerned, so I thought I would ask for other opinions before actually implementing the code.

推荐答案

这是博客文章.它说明了一种更好的处理方法.

Here's a blog post which I would strongly recommend you reading. It illustrates a better approach for handling this.

这篇关于控制器中Ajax Action方法上的Authorize属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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