rest – 基于权限从WebApi端点进行上下文序列化

我正在使用Asp.Net Web Api.我希望能够根据连接的客户端访问权限过滤掉响应对象上的某些字段.

例:

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;
            });
    }
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...