授权Ajax通话 [英] Authorize on Ajax call

查看:62
本文介绍了授权Ajax通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有MVC5项目,单击按钮时有一些ajax调用,它调用的控制器具有我创建的自定义属性,因此框架可以将某人重定向到类似于非ajax的登录页面 [Authorize] .

So I have MVC5 project and I have some ajax call when clicking a button, the controller it called have custom attribute I made so the framework can redirect someone to login page similar to non-ajax [Authorize].

自定义属性:

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext context)
    {
        if (context.HttpContext.Request.IsAjaxRequest()) {
            dynamic urlHelper = new UrlHelper(context.RequestContext);
            context.HttpContext.Response.StatusCode = 403;

            context.Result = new JsonResult {
                Data = new {
                    Error = "NotAuthorized",
                    LogOnUrl = urlHelper.Action("Registration", "Membership")
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        } else {
            base.HandleUnauthorizedRequest(context);
        }
    }
}

控制器:

[HttpPost()]
[AjaxAuthorize()]
public void Test()
{
       //do something
}

JavaScript:

Javascript :

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

它在我的本地主机上运行良好,但是当我将其部署到Web服务器时它不起作用.我做了一些检查,结果发现我的jquery脚本中的 xhr.responseText 有不同的结果,这是比较:

it works fine in my localhost, however it doesn't work when I deployed it to my webserver. I did some checking and turned out the xhr.responseText in my jquery script have different result, here's the comparison :

本地主机:

{"Error":"NotAuthorized","LogOnUrl":"/Membership/Registration"} //correct output

网络服务器:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>403 - Forbidden: Access is denied.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>403 - Forbidden: Access is denied.</h2>
  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
 </fieldset></div>
</div>
</body>
</html>

知道为什么会这样吗?

推荐答案

方法1 (首选)

您可以将Response的 TrySkipIisCustomErrors 设置为true.像这样:

You can set TrySkipIisCustomErrors to true for your Responses. Like this:

protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
    if (context.HttpContext.Request.IsAjaxRequest()) {
        dynamic urlHelper = new UrlHelper(context.RequestContext);

        context.HttpContext.Response.TrySkipIisCustomErrors= true;
        context.HttpContext.Response.StatusCode = 403;

        context.Result = new JsonResult {
            Data = new {
                Error = "NotAuthorized",
                LogOnUrl = urlHelper.Action("Registration", "Membership")
            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    } else {
        base.HandleUnauthorizedRequest(context);
    }
}

方法2 您可以通过从 HandleUnauthorizedRequest 中删除此语句来停止发送HTTP状态码 403 .

Method 2 You can Stop Sending end HTTP Status Code 403 by removing this statement from HandleUnauthorizedRequest.

context.HttpContext.Response.StatusCode = 403;

这将告诉您的客户端和服务器此请求已成功.在这种情况下,您的JavaScript代码将如下所示:

This will tell your client and server this this request has succeeded. In that case your javascript code would be look something like this,

$(document).ajaxSuccess(function (e, xhr) {
    var response = $.parseJSON(xhr.responseText);
    if (typeof(response.Error) !== 'undefined') {
        window.location = response.LogOnUrl;
    }
});

这篇关于授权Ajax通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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