如何将参数传递给我的自定义过滤器

时间:2013-06-07 12:40:05

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

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

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,因此我很容易地发送参数,无论我是否需要发送EntityNameFieldNameNewValue,{{1 }}

如何从控制器发送值?

1 个答案:

答案 0 :(得分:0)

首先,您可能希望覆盖OnActionExecuted事件。

要传递参数,您必须使用参数:

创建构造函数
private paramType param;

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