skip to Main Content

I have some code below so that when a user calls a method in an mvc controller it does some checks to see if it is an Ajax call or not. If Ajax it returns a json response else it returns a url string (Security page). When I run in visual studio the code works perfectly so it recognises the call is an ajax call but on a production server variable "isAjax" is set to false. Is there any reason why it would work locally in visual (local iis) but not on a server?

var isAjax = (filterContext.RequestContext.HttpContext.Request["X-Requested-With"] == "XMLHttpRequest") ||
                             ((filterContext.RequestContext.HttpContext.Request.Headers != null) &&
                             (filterContext.RequestContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

On the network tab in the browser it shows that it is being passed (image below)

Network tab

2

Answers


  1. public ActionResult GetData()
    {
      if(Request.IsAjaxRequest())
            return RedirectToAction("AjaxRequest");
      else
            return RedirectToAction("NonAjaxRequest");
    }
    

    Instead of checking the headers you can check the current request at controller level.

    Login or Signup to reply.
  2. AJAX calls will have a header named X-Requested-With, and the value will be XMLHttpRequest. So you can check like this:

    bool isAjaxRequest = request.Headers["X-Requested-With"] == "XMLHttpRequest";
    

    Otherwise you can use the System.Web.MVC reference and use the function.

    bool isAjaxRequest = Request.IsAjaxRequest();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search