@André Scarteziniの答えに従って、私が書いたサンプルコードを追加してみましょう。
投稿されたデータをWeb APIメソッドに自動的に記録するActionFilterです。これは、仕事をするのに最適なソリューションではなく、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の配列を返します) –