1

我研究了如何检查是否通过 C# 中的 AJAX 发送请求,但它似乎对我不起作用。我的代码如下。我使用一种方法在客户端 AJAX 页面(在我的情况下,正在使用 activeXobject)。ajax 页面正在检查 ajax 属性服务器端的请求,但 X-Requested-With 属性均未返回任何内容(打印时出现空白)。想法?

Ajax 方法 (Javascript)

/*
* Ajax page loads with url
* @param url : URL to call for ajax page load
* @param element : Element ID to be updated
*/
function ajax(url, element) {
    UtilLogger.log(HtmlLogger.INFO, "-AJAX Call for " + url + " in " + element + "-");
    var ajx;
    if (window.HXMLHttpRequest) {
        UtilLogger.log(HtmlLogger.FINE, "Using XMLHttpRequest");
        ajx = new XMLHttpRequest();
    }
    else {
        UtilLogger.log(HtmlLogger.FINE, "Using ActiveXObject");
        ajx = new ActiveXObject("Microsoft.XMLHTTP");
    }
    ajx.open("GET", url, true);
    ajx.send();
    ajx.onreadystatechange = function () {
        if (ajx.readyState == 4 && ajx.status == 200) {
            document.getElementById(element).innerHTML = ajx.responseText;
        }
        else if (ajx.readyState == 4 && ajx.status == 400) {
            alert("Page Error. Please refresh and try again.");
        }
        else if (ajx.readyState == 4 && ajx.status == 500) {
            alert("Server Error. Please refresh and try again.");
        }
    }
    UtilLogger.log(HtmlLogger.INFO, "-END AJAX Call for " + url + " in " + element + "-");
}

Ajax 登录检查 (C#)

/* Checks for ajax request validity
 * @param HttpResponse resp : response to redirect if not ajax request
 * @param HttpRequest req : request to check for ajax
 */
public static void checkAjax(HttpResponse resp, HttpRequest req)
{
    if(req == null || 
        (req["X-Requested-With"] != "XMLHttpRequest" && 
        (req.Headers != null && req.Headers["X-Requested-With"] != "XMLHttpRequest"))){
           // resp.Redirect("./ajaxerror.aspx");
            resp.Write(req["X-Requested-With"] + ":" + req.Headers["X-Requested-With"]);
    }
}
4

1 回答 1

2

您的客户端请求不会自动向您的服务器提供任何“X-Requested-With”标头或查询参数(但某些框架(如 Microsoft AJAX)会提供)。AJAX 调用与任何 HTTP 请求一样工作,以添加一些标头:

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
于 2012-04-18T12:45:41.393 回答