如何传递参数到我的自定义过滤器
本文关键字:自定义 过滤器 我的 何传递 参数 | 更新日期: 2023-09-27 18:17:19
如何传递参数到我的自定义过滤器。我试了下面的方法,但我不知道如何传递参数。
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,所以我很容易发送参数,无论我是否需要发送EntityName
, FieldName
, NewValue
, Oldvalue
如何从控制器发送值
首先你可能想要重写OnActionExecuted事件。
要传递参数,必须创建带有参数的构造函数:
private paramType param;
public AuditAttribute(paramType param)
{
this.param = param;
}