最近在做个接口功能,业务需求需要记录请求报文,即保存请求参数,设计逻辑在OnActionExecuted获取参数加以保存。但是处理过程不是很顺利,折腾后记录下。
MVC中的ActionFilterAttribute可以继承两个父类(using System.Web.Mvc)和(using System.Web.Http.Filters),分别对应的是Controller和ApiController中,顺序不可反。如果ActionFilterAttribute继承using System.Web.Mvc的类将属性标记到Web Api的Controller或Action上,事件是触发不了的。
获取参数比较折腾,直接从context.Request.Form中是获取不到参数的,继承的东西不懂方式也不一样。
1 using System.Web.Mvc OnActionExecuted的参数获取
public virtual void OnActionExecuted(ActionExecutedContext filterContext);
//详细的请见 参考博客,很详细
//直接根据参数名获取参数
var warterNo = context.Controller.ValueProvider.GetValue("WarterNo").AttemptedValue;
//获取第一个对象里的所有参数
var paramss = context.ActionDescriptor.GetParameters();
if (paramss.Length > 0)
{
var itemType = paramss[0].ParameterType;
PropertyInfo[] infos = itemType.GetProperties();
Dictionary<string, string> parmsObj = new Dictionary<string, string>();
foreach (PropertyInfo info in infos)
{
if (info.CanRead)
{
var propertyValue = context.Controller.ValueProvider.GetValue(info.Name);// 暂不支持多层嵌套 后期优化?
if (!parmsObj.ContainsKey(info.Name))
{
parmsObj.Add(info.Name, null == propertyValue ? "" : propertyValue.AttemptedValue);
}
}
}
}string json = JsonConvert.SerializeObject(parmsObj);
2 using System.Web.Http.Filters
public override void OnActionExecuted(HttpActionExecutedContext context)
var dicParams= context.ActionContext.ActionArguments;
var model = dicParams["参数名"] ;
比如我的
var model = dicParams["model"] as AutoBorrowApiModel;