我尝试了Request.IsAjaxRequest,但这在WebForms中不存在。我正在进行JQuery ajax调用。如何在C#中检查这是否是ajax请求?
您可以创建自己的扩展方法,就像
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"); }