0

In my action filter, I am getting the user visited URL through this code.

MyActionFilter:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;

    }
}

I need to pass the originalPath to the main controller in order to save the URL into db. How do I pass the url from action filter to main controller?

Main controller:

public class HomeController : Controller
{

    private readonly MyLogEntities _db = new MyLogEntities();
   [LogActionFilter]
    public ActionResult Index()
    {
        return View();
    }
    [LogActionFilter]
    public ActionResult About(int id)
    {
        ViewBag.Message = "Your application description page.";
        var usr = _db.UserLogs.SingleOrDefault(u => u.ID == id);
        var inputUser = ConfigurationManager.AppSettings["INPUT_USER"].ToString().ToLower();
        usr.Date = DateTime.Now;
        usr.url= originalPath; // need to get this from action filter
        usr.UserName = inputUser;
        _db.Logs.Add(usr);
        _db.Entry(usr).State = EntityState.Added;
        _db.SaveChanges();
        return View();
    }
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}
Anderson Pimentel
  • 4,422
  • 2
  • 27
  • 48
Nav
  • 71
  • 9
  • 1
    You could implement the whole logging inside the action filter. It would make your code cleaner. Anyway, you could use `ActionExecutingContext.ActionParameters` to pass data or why don't you simply get it where you need it, without the action filer at all? The controller has the same context while the action is called. – ZorgoZ Jan 15 '19 at 18:03
  • The easy answer is to throw it into `ViewBag` or `HttpContext.Item[]`. The slightly harder answer is to log it directly from the filter, although to be elegant you should inject the service ([here's how](https://stackoverflow.com/questions/36109052/inject-service-into-action-filter/36109690)). – John Wu Jan 15 '19 at 18:08
  • @ZorgoZ sounds good. I never thought of this one. how can I implement the whole logging inside the action filter? – Nav Jan 15 '19 at 18:52

0 Answers0