Asp.Netmvc:ActionFilterAttributeを使用して操作ログを記録する
12356 ワード
1.ActionFilterAttributeの基本紹介:引用ネーミングスペース:using system.web.mvc、これはsystemで重要です.web.Http.Filterの下にはActionFilterAttributeクラスもありますが、大きな違いがあります.ActionFilterAttributeはActionフィルタクラスであり、actionの実行前、actionの実行後、および操作結果の発行前、および操作結果の実行後に実行できます.2.操作ログのクラスを構築する
public class OperateLog
{
///
/// Id
///
[DisplayName(" Id")]
public Guid Id { get; set; }
///
/// Id
///
[DisplayName(" Id")]
public Guid OperatorId { get; set; }
///
///
///
[DisplayName(" ")]
public Operator Operator { get; set; }
///
///
///
[DisplayName(" ")]
public DateTime OperateTime { get; set; }
///
///
///
[DisplayName(" ")]
public string Operate { get; set; }
///
///
///
[DisplayName(" ")]
public int Level { get; set; }
///
///
///
[NotMapped]
[DisplayName(" ")]
public ImportantLevel LevelEnum
{
get { return (ImportantLevel)Level; }
set { Level = (int)value; }
}
///
///
///
[DisplayName(" ")]
public string Description { get; set; }
///
///
///
public enum ImportantLevel { = 0, = 1 }
}
3. ActionFilterAttribute , OnActionExecuted() Action 。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class OperationLogAttribute: ActionFilterAttribute
{
///
///
///
///
public OperationLogAttribute(string operate,ImportantLevel level=ImportantLevel. ,string description=null)
{
this.Operate = operate;
Level = level;
Description = description;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (Common.Common.CurrentUser == null) return;
AdministrativeSupervisionContext db = new AdministrativeSupervisionContext();
OperateLog operateLog = new OperateLog();
operateLog.Id = Guid.NewGuid();
operateLog.OperateTime = DateTime.Now;
operateLog.Operate = Operate;
operateLog.Description = Description;
operateLog.LevelEnum = Level;
operateLog.OperatorId = Common.Common.CurrentUser.Id;
db.OperateLogs.Add(operateLog);
db.SaveChanges();
base.OnActionExecuted(filterContext);
}
///
/// Id
///
public Guid OperatorId { get; set; }
///
///
///
public DateTime OperateTime { get; set; }
///
///
///
public string Operate { get; set; }
///
///
///
public ImportantLevel Level { get; set; }
///
///
///
public string Description { get; set; }
}
3. ActionFilterAttribute , Action 。
[Attributes.OperationLog(" ",OperateLog.ImportantLevel. )]
public virtual async Task DeleteConfirmed(Guid id)
{
try{
OperateLog operateLog = await db.OperateLogs.FindAsync(id);
db.OperateLogs.Remove(operateLog);
await db.SaveChangesAsync();
//return RedirectToAction("Index");
return Json(new JsonResultModel { Status = (int)JsonResultStatus.Success, Message = " " });
}catch{
return Json(new JsonResultModel { Status = (int)JsonResultStatus.Error, Message = " " });
}
}