无法将XMLHttpRequest()识别为IsAjaxRequest? [英] XMLHttpRequest() not recognized as a 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
您始终可以查看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屋!