2012-10-02 34 views
11

我想能夠在web api ActionFilter中做一些權限檢查,所以我需要能夠拉出對象ID。我可以在GET上執行此操作,因爲我可以訪問RouteData,但是可以在PUT \ POST的操作篩選器中訪問searlized viewModel對象嗎?Web API ActionFilterAttribute是否可以訪問模型?

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? 
    } 

回答

12

你試過了ActionArguments屬性嗎?

+2

filterContext.ActionParameters – Felix

+0

真棒,謝謝! – NullReference

+0

在MVC5中,filterContext.ActionParameters已成爲filterContext.ActionDescriptor.GetParameters()(返回一個System.Web.Mvc.ParameterDescriptor數組) –

0

你必須通過此屬性訪問序列模型:

actionContext.Response.Content

這可能是一些工作,以確定如何處理從該財產,雖然反序列化。 Web API文檔現在非常稀少,但是here is the official docs.Response.Content類型是HttpReponseMessage因此,您應該通過搜索找到更多關於反序列化的詳細信息。

0

讓我關注@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 
    } 
相關問題