Technolar
Technolar

Reputation: 35

ASP.NET MVC find what page sent the Ajax request

I'm implementing profiling for our site, and I'm basically just using timers in Application_BeginRequest() and Application_EndRequest() to track the request times.

The issue is that in Application_EndRequest(), I can get the Ajax request's URL by Request.RawUrl, but how can I get which page sent this request?

Upvotes: 1

Views: 1447

Answers (2)

Ajay Kelkar
Ajay Kelkar

Reputation: 4621

Along with that you can use below code to pass the requesting page url

$(document).ready(function() {
     jQuery.ajaxSetup({
          beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.setRequestHeader('X-Referrer', location.href);//this will do
                return xhr;
          }
     });
});

and on server side , use an actionfilter and put IsAjaxRequest property in your controller class

[AjaxDetector]
public abstract class SomeController : Controller
{
   public bool IsAjaxRequest { get; set; }
   public string Referrer { get; set; }
}

public class AjaxDetector : ActionFilterAttribute  
{  
    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    {   
        SomeController someController = filterContext.Controller as SomeController;
        if (myController != null)
        {
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] != null
                && filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                someController.IsAjaxRequest = true;
                someController.Referrer=filterContext.HttpContext.Request.Headers["X-Referrer"]
            }
            else
            {
                someController.IsAjaxRequest = false;
            }
        }
    }
}

Upvotes: 1

Dimitris Kalaitzis
Dimitris Kalaitzis

Reputation: 1426

You can check Request.UrlReferrer to get the page from which the request originated but keep in mind that some browser may not send referer in ajax requests and you should account for this case in your code.


Alternatively, you should pass an additional parameter containing the current url in all your ajax calls.

Upvotes: 3

Related Questions