小编典典

如何在代码隐藏中检查请求是否为Ajax-ASP.NET Webforms

ajax

我试过了,Request.IsAjaxRequest但这在WebForms中不存在。我正在进行JQuery
ajax调用。如何在C#中检查这是否是ajax请求?


阅读 250

收藏
2020-07-26

共1个答案

小编典典

您可以创建自己的扩展方法,就像MVC代码中的方法一样

例如

public static bool IsAjaxRequest(this HttpRequest request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }

    return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
}

查尔斯· HTH

编辑: 实际上,回调请求也是ajax请求,

    public static bool IsAjaxRequest(this HttpRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }
        var context = HttpContext.Current;
        var isCallbackRequest = false;// callback requests are ajax requests
        if (context != null && context.CurrentHandler != null && context.CurrentHandler is System.Web.UI.Page)
        {
            isCallbackRequest = ((System.Web.UI.Page)context.CurrentHandler).IsCallback;
        }
        return isCallbackRequest || (request["X-Requested-With"] == "XMLHttpRequest") || (request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
2020-07-26