Asp.net MVC通过自定义特性实现Action日志记录

一、自定义特性

/// <summary>
/// 描述特性
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class DescribeAttribute : Attribute
{
private string _funDescribe; public DescribeAttribute() { } public DescribeAttribute(string funDescribe)
{
this._funDescribe = funDescribe;
} public string FunDescribe
{
get { return _funDescribe; }
}
}

二、在Action上面加入特性

[Describe("系统主页面")]
public ActionResult Index()
{
return View();
}

三、继承ActionFilterAttribute实现LogFilter日志

public sealed class LogFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
} object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(DescribeAttribute), false);
if (attrs.Length > )
{
string funDescribe = ((DescribeAttribute)attrs[]).FunDescribe;
}
base.OnActionExecuted(filterContext);
}
}

四、在App_Start文件夹下面加入全局日志过滤器

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
filters.Add(new HandleErrorAttribute());
filters.Add(new LogFilter());
}
}
上一篇:异常问题解决Error:Execution failed for task ':app:processDebugManifest'


下一篇:document.compatMode的CSS1compat