WebApi自定义过滤器

时间:2015-09-01 13:33:25

标签: c# asp.net-web-api

我正在开发一个需要将所有请求保存到数据库的日志。 我创建了一个自定义过滤器并注册了它,但是当我请求控制器时它不会被调用。

这是LogFilter.cs

 public class LogFilter : System.Web.Http.Filters.FilterAttribute, IFilter
{
    public void OnActionExecuting(ActionExecutedContext filterContext)
    {
        try
        {
            string entity = "";
            using (StreamReader sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
            {
                entity = sr.ReadToEnd();
            }

            logModel.RequestLog rl = new logModel.RequestLog();
            rl.IP = filterContext.HttpContext.Request.UserHostAddress;
            rl.Type = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString().ToUpper();
            rl.URL = filterContext.HttpContext.Request.Url.OriginalString;
            rl.Operation = filterContext.HttpContext.Request.HttpMethod;
            rl.RequestDate = DateTime.Now;
            if (!string.IsNullOrEmpty(entity))
                rl.Entity = entity;

            filterContext.HttpContext.Request.Cookies.Add(new HttpCookie("reqID", new deviceLog.RequestLog().Add(rl).ID.ToString()));
        }
        catch { }
    }

Global.asax中

 protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);


        WebApiConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
    }

WebApiConfig.cs

 public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: DEFAULT_API_NAME,
            routeTemplate: DEFAULT_API_ROUTE,
            defaults: new
            {
                parameter1st = RouteParameter.Optional,
                parameter2nd = RouteParameter.Optional,
                parameter3rd = RouteParameter.Optional
            }
        );

        // remove support for xml
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // force json indentation
        config.Formatters.JsonFormatter.Indent = true;
    }
    public static void RegisterGlobalFilters(System.Web.Http.Filters.HttpFilterCollection filters)
    {
        filters.Add(new LogFilter());
    }

1 个答案:

答案 0 :(得分:2)

HttpActionContext命名空间

下的Web Api需要System.Web.Http.Filters
public override void OnActionExecuting(HttpActionContext actionExecutedContext)
{
    base.OnActionExecuted(actionExecutedContext);
}

请注意override此处