我正在使用 Asp.Net Web Api。我希望能够根据连接的客户端访问权限过滤掉响应对象上的某些字段。
例子:
class Foo
{
[AccessFilter("Uberlord")]
string Wibble { get; set; }
string Wobble { get; set; }
}
返回数据时归档
Wibble
仅当当前用户上下文可以满足“Uberlord”的值时才应返回。我正在探索三种途径,但我没有找到可行的解决方案:
我的问题是:
另一个好处是使用相同的机制从入站请求对象的字段中删除值。
我错过了一个明显的钩子(Hook)吗?这是否已通过其他方式解决?
最佳答案
它实际上比我最初想象的要简单得多。我没有意识到 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;
});
}
}
有关如何实现委托(delegate)处理程序并将其添加到管道的 Microsoft 文章。 HTTP Message Handlers in ASP.NET Web API
关于rest - 基于权限的 WebApi 端点的上下文序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172076/