例:
class Foo { [AccessFilter("Uberlord")] string Wibble { get; set; } string Wobble { get; set; } }
返回数据时,只有当前用户上下文可以满足“Uberlord”的值时才应返回提交的Wibble.
我正在探索三种途径,但我没有一个有效的解决方案:
>自定义WebApi MediaTypeFormatter.
>自定义json.net IContractResolver.
>某种用于操纵响应对象的控制器的AOP包装器
我的问题是:
>自定义格式化程序感觉不是正确的位置,但可能是唯一的选择.
>自定义json序列化程序无法访问当前上下文,因此我必须解决这个问题.
>使用前两个选项,您需要针对每种响应格式,json,xml,某些自定义格式等进行特定实现.这意味着如果支持其他响应类型,则需要自定义格式化程序/序列化程序来防止敏感数据泄漏.
> AOP控制器包装器需要大量反射.
另一个好处是使用相同的机制从入站请求对象的字段中去除值.
我错过了一个明显的钩子吗?这是通过另一种方式解决的吗?
解决方法
DelegatingHandler
可用于操纵响应以及
Web Api Pipeline中的请求.
Lifecycle of an ASP.NET Web API Message
Delegating Handler
Delegating handlers are an extensibility point in the message pipeline allowing you to massage the Request before passing it on to the rest of the pipeline. The response message on its way back has to pass through the Delegating Handler as well,so any response can also be monitored/filtered/updated at this extensibility point.
Delegating Handlers if required,can bypass the rest of the pipeline too and send back and Http Response themselves.
例
以下是DelegatingHandler的示例实现,它可以操作响应对象或完全替换它.
public class ResponseDataFilterHandler : DelegatingHandler { protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) { return base.SendAsync(request,cancellationToken) .ContinueWith(task => { var response = task.Result; //Manipulate content here var content = response.Content as ObjectContent; if (content != null && content.Value != null) { ((SomeObject)content.Value).SomeProperty = null; } //Or replace the content response.Content = new ObjectContent(typeof(object),new object(),new JsonMediaTypeFormatter()); return response; }); } }