讓我關注@André Scartezini的回答,並添加我寫的示例代碼。
它是一個ActionFilter,用於將發佈的數據自動記錄到Web API方法。這不是完成這項工作的最佳解決方案,而只是一個示例代碼,以展示如何從ActionFilter屬性內部訪問模型。
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace LazyDIinWebApi.Models
{
public class LogPostDataAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutingAsync(
HttpActionContext actionContext,
CancellationToken cancellationToken)
{
Collection<HttpParameterDescriptor> parameters
= actionContext.ActionDescriptor.GetParameters();
HttpParameterDescriptor parameter
= parameters == null ? null : parameters.FirstOrDefault();
if (parameter != null)
{
string parameterName = parameter.ParameterName;
Type parameterType = parameter.ParameterType;
object parameterValue =
actionContext.ActionArguments == null && !actionContext.ActionArguments.Any() ?
null :
actionContext.ActionArguments.First().Value;
string logMessage =
string.Format("Parameter {0} (Type: {1}) with value of '{2}'"
, parameterName, parameterType.FullName, parameterValue ?? "/null/");
// use any logging framework, async is better!
System.Diagnostics.Trace.Write(logMessage);
}
base.OnActionExecuting(actionContext);
}
}
}
這是如何使用它:
// POST: api/myapi
[LogPostData]
public void Post(MyEntity myEntity)
{
// Your code here
}
filterContext.ActionParameters – Felix
真棒,謝謝! – NullReference
在MVC5中,filterContext.ActionParameters已成爲filterContext.ActionDescriptor.GetParameters()(返回一個System.Web.Mvc.ParameterDescriptor數組) –