【问题标题】:How to pass parameter to my custom filters如何将参数传递给我的自定义过滤器
【发布时间】:2013-06-03 18:39:36
【问题描述】:

如何将参数传递给我的自定义过滤器。我尝试了以下方式,但我不知道如何传递参数。

public class AuditAttribute : ActionFilterAttribute
    {
        private PCBAuditEntities _entity = new PCBAuditEntities();

        public bool IsRequired { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            //Stores the Request in an Accessible object
            HttpRequestBase request = filterContext.HttpContext.Request;
            string actionname = filterContext.ActionDescriptor.ActionName;
            //Generate an audit
            Audit audit = new Audit()
                {

                    IpAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress,
                    UrlAccessed = request.RawUrl,
                    TimeAccessed = DateTime.UtcNow,
                    UserName = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous",
                    Actionname = actionname,
                    EntityName ="" ,//what entity i changed?
                    FieldName = "",// How to find the FieldName?
                    Operations = "",// what operatins client did?
                    NewValue = "",// what is the new value?
                    Oldvalue = "",// what is the old value?

                };
            _entity.Audits.Add(audit);
            _entity.SaveChanges();

            base.OnActionExecuting(filterContext);
        }



    }

    [Audit(IsRequired = true)]
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

在上面的代码IsRequired中,我们只指定了true或false,所以我很容易发送参数是否需要发送EntityNameFieldNameNewValueOldvalue

如何从控制器发送值?

【问题讨论】:

  • How can i send the above values from controller? - 您订阅了OnActionExecuting 事件,该事件在控制器动作运行之前执行。所以谈论将这些值从控制器发送到动作过滤器是没有意义的。这就像在您实际购买汽车之前尝试开车一样。
  • @DarinDimitrov 抱歉,我不了解自定义过滤器

标签: c# asp.net-mvc asp.net-mvc-4 filter


【解决方案1】:

首先可能你想覆盖 OnActionExecuted 事件。

要传递参数,您必须创建带参数的构造函数:

private paramType param;

public AuditAttribute(paramType param)
{
     this.param = param;
}

【讨论】:

  • 好吧..控制器怎么写
猜你喜欢
  • 2022-06-24
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 2017-02-24
  • 2014-01-23
  • 1970-01-01
相关资源
最近更新 更多