0

我正在使用 ajax 不显眼,当它到达我的自定义授权标签时,状态代码已设置,我已经准备好 json 数据,但是当它返回信息时,状态代码被捕获在控制台中并说例如,“加载失败资源:服务器响应状态为 403(禁止)。” 我在 onfailure ajax 选项中放置了警报,并且那里没有任何东西被触发。似乎它没有将状态码错误视为失败的 ajax 调用。如何处理 onFailure ajax 选项中的状态码错误?

                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var urlHelper = new UrlHelper(filterContext.RequestContext);
                    filterContext.HttpContext.Response.StatusCode = 403;
                    filterContext.Result = new JsonResult()
                    {
                        Data = new
                        {
                            Error = "NotAuthorized",
                            LogOnUrl = urlHelper.Action("AccessDenied", "Error", new { area=""})
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }

这是在我的自定义授权属性中。

@Ajax.ActionLink("Company", "Company", "Admin", null, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "centerAdmin", HttpMethod = "POST", OnComplete = "Oncomplete", OnSuccess = "OnSuccess", OnFailure = "OnFailure" })

我的 Ajax 不显眼的调用

<script>

function OnSuccess(ajaxContext)
{
    alert("dfgsdfgsdfgsdfgfdgsdfgddf");
}
function OnFailure(ajaxContext) {
    alert("dfgsdfsdfgdfgsgsdf");
}
function Oncomplete(ajaxContext) {
    alert("dfgsddfffffffffffffffffffffgsdf");
}

简单的警报,看看它是否触发了这些事件中的任何一个。

4

2 回答 2

0

由于您可能厌倦了我用更多的问题来回答您的问题,因此可以尝试一下。它至少应该属于您的 OnFailure 处理程序。不要将 Result 设置为 json 对象,而是将其设置为 HttpStatusCodeResult。

filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden, "You are not authorized to access this page!"); // Set whatever status code is appropriate.

不确定是否传递登录 url 或其他 json 参数,但这应该是一个开始。我认为您不需要设置响应的状态码。

于 2014-04-07T18:42:32.080 回答
0
$(function () {
$(document).ajaxError(function (e, xhr) {
    debugger;
    if (xhr.status == 403) {
        alert("403");
    }
    alert("not 403");
});

});

经过一番研究,我遇到了这个代码片段,它现在似乎解决了我的问题。

于 2014-04-07T19:23:18.000 回答