如何在代码隐藏中检查请求是否为 ajax - ASP.NET Webforms [英] How to check if request is ajax or not in codebehind - ASP.NET Webforms

查看:21
本文介绍了如何在代码隐藏中检查请求是否为 ajax - ASP.NET Webforms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried the Request.IsAjaxRequest but this does not exist in WebForms. I am making a JQuery ajax call. How do I check if this is a ajax request or not in C#?

推荐答案

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

You could create your own extension method much like the one in the MVC code

例如

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,
查尔斯

HTHs,
Charles

其实回调请求也是ajax请求,

Actually Callback requests are also ajax requests,

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

这篇关于如何在代码隐藏中检查请求是否为 ajax - ASP.NET Webforms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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