I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the ActiveXObject in my case). The page being AJAXed is checking for AJAX properties on the server-side, but neither of the X-Requested-With properties are returning anything (they are blank when printed out). Any suggestions?
Ajax Method (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 Login Check (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"]);
}
}