2012-10-02 10 views
11

Me gustaría poder hacer algunas comprobaciones de permisos en un ActionFilter de api web, así que necesito poder extraer el ID del objeto. Puedo hacer esto en un GET ya que tengo acceso a RouteData, pero ¿es posible acceder al objeto viewModel investigado en un filtro de acción para un PUT \ POST?¿Puede una API web ActionFilterAttribute tener acceso al modelo?

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     if (actionContext == null) 
     { 
      throw new ArgumentNullException("actionContext"); 
     } 

     //Get ID from searlized object and check permissions for a POST\PUT? 
    } 

Respuesta

12

¿Has probado la propiedad ActionArguments?

+2

filterContext.ActionParameters – Felix

+0

impresionante, gracias! – NullReference

+0

En MVC5 filterContext.ActionParameters se ha convertido en filterContext.ActionDescriptor.GetParameters() (devuelve una matriz de System.Web.Mvc.ParameterDescriptor) –

0

usted tiene acceso al modelo en serie a través de esta propiedad:

actionContext.Response.Content

Puede ser algo de trabajo para determinar qué deserializar de esa propiedad sin embargo. La documentación de la API web es bastante escasa en este momento pero here is the official docs. El tipo Response.Content es HttpReponseMessage, por lo que debería encontrar más detalles para la deserialización al buscar eso.

0

Déjame seguir la respuesta de @André Scartezini y agregar un código de muestra que escribí.

Es un ActionFilter para registrar automáticamente los datos publicados en un método Web API. No es la mejor solución para hacer el trabajo, sino solo un código de muestra para mostrar cómo acceder al modelo desde dentro de un atributo de 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); 
     } 
    } 
} 

Y esto es cómo usarlo:

// POST: api/myapi 
    [LogPostData] 
    public void Post(MyEntity myEntity) 
    { 
     // Your code here 
    } 
Cuestiones relacionadas