我已经研究过如何检查是否在C#中通过AJAX发送请求,但它似乎对我不起作用。我的代码如下。我在客户端使用一种方法AJAX页面(在我的例子中,正在使用activeXobject)。 ajaxed页面正在检查ajax属性serverside的请求,但是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"]);
}
}
答案 0 :(得分:2)
您的客户端请求不会自动向您的服务器提供任何“X-Requested-With”标头或查询参数(但是某些框架如Microsoft AJAX会这样做)。一个AJAX调用就像任何HTTP请求一样,添加一些标题:
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");