2

我对 Ajax 请求和重定向有疑问。我尝试创建一个自定义授权属性,如下所示:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute

public override void OnAuthorization(AuthorizationContext filterContext)        
{
    base.OnAuthorization(filterContext);            
    if (filterContext.Result == null || (filterContext.Result.GetType() != typeof(HttpUnauthorizedResult) 
        || !filterContext.HttpContext.Request.IsAjaxRequest()))                
        return;                

    var redirectToUrl = "/login?returnUrl=" + filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;   
    filterContext.Result = (filterContext.HttpContext.Request.ContentType == "application/json"  
        ? (ActionResult)                  
        new JsonResult                  
        { 
            Data = new { RedirectTo = redirectToUrl },                      
            ContentEncoding = System.Text.Encoding.UTF8,                      
            JsonRequestBehavior = JsonRequestBehavior.DenyGet                  
        }                
        : new ContentResult                
        {
            Content = redirectToUrl,                    
            ContentEncoding = System.Text.Encoding.UTF8,                    
            ContentType = "text/html"                
        });                 

    //Important: Cannot set 401 as asp.net intercepts and returns login page            
    //so instead set 530 User access denied                       
    filterContext.HttpContext.Response.StatusCode = 530; //User Access Denied            
    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;                    
}    
} 

但是我的应用程序中的 isAjaxRequest() 总是错误的。即使我从 jquery .ajax() 调用中调用操作。

编辑:包括建议的ajax调用。我的一些 ajax 调用是由 jqGrid 组件进行的。数据类型设置为 JSON,类型为 POST。控制器具有 HTTPPost 装饰。其中一些是直接的 jquery ajax 调用,如下所示:

$("#clientList").change(function () {
    var client = $("#clientList").val();
    $.ajax({
        url: "myurl",
        data: { 'client': client },
        cache: false,
        traditional: true,
        type: 'POST',
        success: function (data) {
            <do something here>
        }
    });
});
4

0 回答 0