2012-10-02 11 views
11

ウェブAPIのActionFilterでいくつかの権限チェックができるようにしたいので、オブジェクトIDを引き出す必要があります。私はRouteDataにアクセスできるのでGETでこれを行うことができますが、PUT \ POSTのアクションフィルタで検索された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プロパティを試しましたか?それはいくつかの作業は、しかし、そのプロパティからデシリアライズするかを決定することであってもよい

actionContext.Response.Content

+2

filterContext.ActionParameters恐ろしい – Felix

+0

、ありがとう! – NullReference

+0

MVC5ではfilterContext.ActionParametersはfilterContext.ActionDescriptor.GetParameters()(System.Web.Mvc.ParameterDescriptorの配列を返します) –

0

あなたは、このプロパティを使用してシリアル化されたモデルへのアクセス権を持っています。 Web APIのドキュメントは現在かなり疎ですが、here is the official docs.HttpReponseMessageのタイプはResponse.Contentです。そのため、それを検索することで、逆シリアル化の詳細を見つける必要があります。

0

@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 
    } 
関連する問題