【问题标题】:XMLHttpRequest() not recognized as a IsAjaxRequest?XMLHttpRequest() 不被识别为 IsAjaxRequest?
【发布时间】:2015-03-09 06:30:31
【问题描述】:

为了在 Ajax 请求会话超时时重定向用户登录页面,我实现了以下自定义属性,

Unauthorize 请求相关代码如下,

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "SessionTimeOut"
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                filterContext.HttpContext.Response.End();
            }
....................

这适用于 ajax 请求 ($.ajax)。

但 filterContext.HttpContext.Request.IsAjaxRequest() 无法将 XMLHttp 请求识别为 ajax 请求。

var xhr = new XMLHttpRequest();
                xhr.open('POST', "...URL");
                xhr.send(formdata);

有没有人遇到过类似的问题?对此有什么解决方案?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-ajax


    【解决方案1】:

    这是 ASP.NET MVC 5 中 IsAjaxRequest() 的代码

    public static bool IsAjaxRequest(this HttpRequestBase request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }
        return request["X-Requested-With"] == "XMLHttpRequest" || (request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
    

    看起来需要依赖请求中的某个标头值 (X-Requested-With) 才能使该函数返回 true。

    这里有更多关于X-Requested-With的信息

    What's the point of the X-Requested-With header?

    您可以随时查看 jQuery $.ajax() 代码本身,了解它是如何设置标题的。老实说,无论如何,如果没有 jQuery,我不会费心去做 ajax,它会为你处理所有这些事情。

    【讨论】:

    • 是的,你是对的,就我而言,在 WebWorker 中我必须使用 XMLHttpRequest 而不是 $.ajax,然后我使用该标头:var _XMLHttpRequest = new XMLHttpRequest(); _XMLHttpRequest.open("POST", . .., 真的); ` _XMLHttpRequest.setRequestHeader("__RequestVerificationToken", ...); ` _XMLHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest"); ` _XMLHttpRequest.responseType = 'json'; ` _XMLHttpRequest.send(...);
    猜你喜欢
    • 2010-11-01
    • 2011-07-31
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2022-01-06
    • 2022-01-14
    相关资源
    最近更新 更多