无法将XMLHttpRequest()识别为IsAjaxRequest? [英] XMLHttpRequest() not recognized as a IsAjaxRequest?

查看:78
本文介绍了无法将XMLHttpRequest()识别为IsAjaxRequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To redirect user to sign in page when session timed out for Ajax request, I implemented following custom attribute,

与未经授权"请求相关的代码如下,

Code related to Unauthorize request is as follows,

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)很好.

This works fine for ajax requests ($.ajax).

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

But filterContext.HttpContext.Request.IsAjaxRequest() does not recognize XMLHttp request as an ajax request.

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

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

Does anyone came across similar issue? what would be a solution for this?

推荐答案

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

Here's the code for IsAjaxRequest() in ASP.NET MVC 5

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.

It looks like there is a dependency on a certain header value (X-Requested-With) being in the request in order for that function to return true.

有关X-Requested-With

X-Requested-With标头的含义是什么?

您始终可以查看jQuery $.ajax()代码本身,以了解如何设置标头.老实说,如果没有jQuery,我不会费心做ajax,它会为您处理所有这些事情.

You could always look at the jQuery $.ajax() code itself to see how that is setting the header. To be honest, I wouldn't bother doing ajax without jQuery anyway, it deals with all of these things for you.

这篇关于无法将XMLHttpRequest()识别为IsAjaxRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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