@André Scartezini 'ün yanıtını takip edeyim ve yazdığım bir örnek kod ekleyelim.
Bu, Web API yöntemine gönderilen verileri otomatik olarak günlüğe kaydetmek için kullanılan bir ActionFilter'tir. Bu işi yapmak için en iyi çözüm değil, yalnızca bir ActionFilter özniteliğinin içinden modele nasıl erişileceğini göstermek için örnek bir kod.
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);
}
}
}
Ve bu nasıl kullanılacağını geçerli:
// POST: api/myapi
[LogPostData]
public void Post(MyEntity myEntity)
{
// Your code here
}
filterContext.ActionParameters – Felix
Müthiş, teşekkürler! – NullReference
MVC5 filterContext.ActionParameters, filterContext.ActionDescriptor.GetParameters() (System.Web.Mvc.ParameterDescriptor dizisini döndürür) haline geldi –