1、 在项目中提到需要添加日志时,我第一印象是使用日志拦截器即: LoggerFilter:ActionFilter,IActionFilter. 2、 但是我需要向日志拦截器传参,这个时候我想传入动态的参数该如何做呢? 比如获取当前登录用户用户名、登录用户IP地址等等。
    使用属性的方式只能传入一些静态值,如何动态传值。

解决方案 »

  1.   


    对的,在HttpContent中,但是使用属性的方式无法动态赋值的,在Action里当然可以。[LoggerFilter()]
    public ActionResult Index()
    {
      
    }
      

  2.   

    public class LoggerFilter : FilterAttribute,IActionFilter
        {
            public void OnActionExecuted(ActionExecutedContext filterContext)
            {
                
                filterContext.Controller.ViewData["ExecutedLogger"] = "公告添加完成,已以写入日志!时间:" + DateTime.Now;
                if (filterContext.HttpContext.Session["ViewCount"] == null)
                {
                    filterContext.HttpContext.Session["ViewCount"] = 0;
                }
                int viewCount = Convert.ToInt32(filterContext.HttpContext.Session["ViewCount"]);
                viewCount++;
                filterContext.HttpContext.Session["ViewCount"] = viewCount;
            }        public void OnActionExecuting(ActionExecutingContext filterContext)
            {
                var obj = filterContext;
                filterContext.Controller.ViewData["ExecutingLogger"] = "正要添加公告,已以写入日志!时间:" + DateTime.Now;
                
            }
        }你想要的都可以从filterContext.HttpContext这个里面取

    filterContext.HttpContext.Session["User"]
      

  3.   


    那您意思就是使用Session传值,如果是使用Session传值的话, 那么一个Action里传上5个值,而且键还不能相同,相同就会后者覆盖前者。那么5个Action就是25个Session。
      

  4.   

    我晕了~
    当前登录用户用户名、登录用户IP地址
    这些都在HttpContent里面,客户端每次请求都会提交
    就如同你把Cookie写到客户端后,以后每次客户端提交请求,都会连同Cookie一起提交。
    因此你用不用 他都摆在那里为什么5个Action就是25个Session呢?
    只有25个来自不同客户端的请求  才会产生25个Session而且我给的例子是用Session,因为我在学 过滤器 的时候 这样方便实现我需要的效果
    如果你把当前的登录用户名写到Cookie中 就用Cookie啊,也是从HttpContent获取到的感觉你的基础.....
    看看
    http://www.cnblogs.com/fish-li/archive/2011/07/31/2123191.html
    还有他的
    细说 Form (表单)
    细说 Cookie还有他的很多文章都很值得看,他写的很用心~