2010-12-08 56 views

回答

43

你可以多建立自己的扩展方法一样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")); 
} 

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

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

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

尝试检查的ScriptManager IsInAsyncPostBack

ScriptManager.GetCurrent(Page).IsInAsyncPostBack 
+0

这是否工作,它们都从jQuery的阿贾克斯以及来自诸如更新面板控件触发Ajax请求? – DotnetDude 2010-12-08 22:14:59

+1

我不确定,所以我写了`try` ;-) – 2010-12-08 22:17:03

1

是, Request.IsAjaxRequest看着标题和X-Requested-With查询字符串,但它似乎你的jQuery不发送X-Requested-With标题。

你可以试试,看看邮件头。它是通过使用招,或者只发送发送的查询字符串通过设置POST网址

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

+0

JQuery发送了X-Requested-With,所以如果我检查每个Karim79的头文件,它就会起作用。但是,Request在基本页面中没有IsAjaxRequest属性。 – DotnetDude 2010-12-08 22:34:31

0

装饰你的类[WebMethod(EnableSession = true)]语法,如果你写的代码下面的函数一样在ajax调用后面并调用相同的函数,您可以确定。

[WebMethod(EnableSession = true)] 
    public static void getData(string JSONFirstData,string JSONSecondData, string JSONThirdData, string JSONForthData, ...) 
    { 
     //code 
    } 
在阿贾克斯URL

URL :'/Codebehind.aspx/getData'

相关问题