我希望能够在web api ActionFilter中进行一些权限检查,所以我需要能够提取对象ID。我可以在GET上执行此操作,因为我可以访问RouteData,但是可以在PUT \ POST的动作过滤器中访问searlized viewModel对象吗?
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?
}
您可以通过此属性访问序列化模型:
actionContext.Response.Content
确定从该属性反序列化的内容可能有些工作。 Web API文档现在非常稀疏但是 这是官方文档。 该 Response.Content
类型是 HttpReponseMessage
所以你应该通过搜索来找到反序列化的更多细节。
让我跟进 @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
}