Search code examples
asp.net-mvchttphttprequestaction-filter

How to capture redirects in ASP.NET MVC


I have an ActionFilter that is successfully capturing page views along with important information from the request. The primary key of this captured entry is then associated with an activity (i.e: Successful Login).

I am trying to now automatically capture Redirects (i.e: RedirectToAction) and associate this with the page view as well. I believe this can be done in my ActionFilter that is capturing page views, but I am unsure if there is a way to tell from the OnActionExecuting context whether or not the GET request is coming from a redirect.

Is there a way to tell from an HttpRequest / ActionExecutingContext(or ActionExecutedContext) whether or not the page is coming from a redirect?

Thanks!


Solution

  • RedirectToAction returns a RedirectToRouteResult

    In the OnActionExecuted method of your filter -

    if (filterContext.Result is RedirectResult)
    {
        // It was a RedirectResult
        var result = filterContext.Result as RedirectResult;
        var url = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
    }
    else if (filterContext.Result is RedirectToRouteResult)
    {
        // It was a RedirectToRouteResult
        var result = filterContext.Result as RedirectToRouteResult;
        var url = UrlHelper.GenerateUrl(result.RouteName, null, null, result.RouteValues, RouteTable.Routes, filterContext.RequestContext, false);
    }