AspNet web api 和mvc 过滤器差异
最近在维护老项目。定义个拦截器记录接口日志。但是发现不生效
最后发现因为继承的 ApiController不是Controller
只能用 System.Web.Http下的拦截器生效。所以现在总结归纳一下
Web Api: System.Web.Http.Filters.ActionFilterAttribute 继承该类
Mvc: System.Web.Mvc.ActionFilterAttribute 继承该类
Mvc:
提供4个重写方法
OnActionExecuting 执行前
OnActionExecuted 执行后
OnResultExecuting 返回前
OnResultExecuted 返回后
Web Api:
提供4个重写方法
OnActionExecuting 执行前 OnActionExecutingAsync 执行前(异步)
OnActionExecuted 执行后 OnActionExecutedAsync 执行后(异步)
根据自己需求重写方法。然后注入
注入有2种方法
1. Web Api 和 Mvc 通用的。直接打特性。作用域为打了特性的 Class / Action
我是新建了一个类继承基类避免全局+了。
2.全局注入Filter:
Mvc:![]()
在FilterConfig下注入
Web Api:
在WebApiConfig下注入
=====================后续问题记录==================================
做接口日志拦截器。发现个问题。GET参数可以拿到。POST 参数 content用AsString方法拿不到。但是用Stream方法可以拿到。 最终代码如下
var log = new ActionLog();
log.UserId = PayUsersHelper.Instance.GetUserID().ToString();
if (actionExecutedContext.Request != null)
{
log.Uri = actionExecutedContext.Request?.RequestUri?.AbsolutePath?.ToString() ?? "";
log.Method = actionExecutedContext.Request?.Method?.Method;
if (log.Method.Equals("GET"))
log.parameters = actionExecutedContext.Request?.RequestUri?.Query;
else
{
log.parameters = await actionExecutedContext.Request?.Content?.ReadAsStringAsync();
if (string.IsNullOrEmpty(log.parameters))
{
Stream stream = await actionExecutedContext.Request?.Content?.ReadAsStreamAsync();
stream.Position = 0;
Encoding encoding = Encoding.UTF8;
var reader = new StreamReader(stream, encoding);
string result = reader.ReadToEnd();
log.parameters = result;
}
}
}
if (actionExecutedContext.Response != null)
{
log.Response = await actionExecutedContext.Response?.Content?.ReadAsStringAsync() ?? "";
}
if (actionExecutedContext.Exception != null)
{
var errObj = new
{
msg = actionExecutedContext.Exception.Message,
stacktrace = actionExecutedContext.Exception.StackTrace
};
log.ErrorMsg = JsonConvert.SerializeObject(errObj);
}
if (!string.IsNullOrEmpty(log.ErrorMsg))
log.Status = 1;
LoggerHelp.Log(JsonConvert.SerializeObject(log));
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/ce3aec9b59.html
