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

问题描述 投票:26回答:6

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

asp.net jquery ajax webforms
6个回答
46
投票

您可以像MVC code中的那样创建自己的扩展方法

EG

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"));
}

HTHS, 查尔斯

编辑:实际上回调请求也是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");
    }

4
投票

尝试检查ScriptManager IsInAsyncPostBack

ScriptManager.GetCurrent(Page).IsInAsyncPostBack

3
投票

通常,您需要测试X-Requested-With标头,确保其值为“XMLHttpRequest”。我不是C#开发人员(但是),但快速谷歌搜索说在C#中它是这样的:

Request.Headers["X-Requested-With"] == "XMLHttpRequest";

1
投票

是的,Request.IsAjaxRequest查看X-Requested-With的标题和查询字符串,但似乎你的jquery没有发送X-Requested-With标题。

您可以尝试使用Fiddler查看它发送的标头,或者只是通过将POST网址设置为查询字符串来将其发送到查询字符串中

/whatever.aspx?x-requested-with=XMLHttpRequest


0
投票

[WebMethod(EnableSession = true)]syntax装饰你的类,就像你在后面的代码中编写以下函数并从ajax调用调用相同的函数,你将确定。

[WebMethod(EnableSession = true)]
    public static void   getData(string JSONFirstData,string JSONSecondData, string JSONThirdData, string JSONForthData, ...)
    {
       //code
    }

在Ajax URL中就像URL :'/Codebehind.aspx/getData'


0
投票

我创建了一个我使用的扩展:

internal static bool IsAjaxRequest(this HttpRequestMessage request)
{
    return request != null && request.Headers.Any(h => h.Key.Equals("X-Requested-With", StringComparison.CurrentCultureIgnoreCase) &&
        h.Value.Any(v => v.Equals("XMLHttpRequest", StringComparison.CurrentCultureIgnoreCase)));
}
© www.soinside.com 2019 - 2024. All rights reserved.