我在使用JSON和AJAX时遇到了一些问题。我有一个认证类,它具有以下逻辑:
每次用户发出请求时都会调用此HandleUnauthorizedRequest()
,此方法会检查用户是否已登录。如果没有,则重定向到登录页面。
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (ApplicationSession.CurrentUserId == 0)
{
string filepath = System.Web.HttpContext.Current.Server.MapPath("~\\Log\\");
string url = string.Format("{0}?reason=nav", System.Web.Security.FormsAuthentication.LoginUrl);
Utility.LogFileWrite("Step 1: LoginUrl" + System.Web.Security.FormsAuthentication.LoginUrl, filepath);
Utility.LogFileWrite("Step 1.1: url" + url, filepath);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var redirectResult = filterContext.Result as RedirectResult;
if (filterContext.Result is RedirectResult)
{
// It was a RedirectResult => we need to calculate the url
var result = filterContext.Result as RedirectResult;
url = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
}
else if (filterContext.Result is RedirectToRouteResult)
{
// It was a RedirectToRouteResult => we need to calculate
// the target url
var result = filterContext.Result as RedirectToRouteResult;
url = UrlHelper.GenerateUrl(result.RouteName, null, null, result.RouteValues, RouteTable.Routes,
filterContext.RequestContext, false);
}
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.Result = new JsonResult
{
Data = new {Redirect = url},
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
};
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
string json = new JavaScriptSerializer().Serialize(filterContext.Result);
Utility.LogFileWrite("Step 2: Result:" + json, filepath);
}
else
{
//non-ajax request
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Account",
action = "Login"
})
);
//base.HandleUnauthorizedRequest(filterContext);
}
}
}
}
在视图中我添加了以下脚本:
jQuery(document).ajaxStart(function () {
//show ajax indicator
$('#map_loading').show();
}).ajaxStop(function () {
//hide ajax indicator
$('#map_loading').hide();
}).ajaxSuccess(function (event, request, settings) {
}).ajaxError(function (event, request, settings) {
debugger;
if (request.status == 403) {
var json = $.parseJSON(request.responseText);
if (request.responseJSON.Redirect) {
window.location.replace(request.responseJSON.Redirect);
}
}
});
所以,我的问题是当用户没有登录时,它进入了ajaxError函数,但是有" request"它不会返回JSONResult。
此功能在本地服务器上运行正常,但是在运行时我收到错误:
未捕获的TypeError:无法读取属性'重定向'未定义的
在本地服务器上,我得到一个JSON对象Local AjaxError Method Data
但是当Live我没有得到JSON对象。我没有使用responseText而是默认获得403 Html Page,如下所示Live AjaxError Method Data
任何人都可以给我一个解决方案,了解如何在ajax函数中获得Json结果?为什么它在本地工作但不能在现场工作。