我研究了如何检查是否通过 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"]);
}
}