【问题标题】:WCF REST Service Update HeaderWCF REST 服务更新标头
【发布时间】:2011-01-21 22:12:46
【问题描述】:

使用 RequestInterceptor 可以从请求中提取 HTTP 标头并对其进行一些处理。还可以更新响应。但是,有没有办法在请求本身中更新和/或插入 HTTP 标头,以便后续处理器(例如拦截器、授权管理器)?

【问题讨论】:

    标签: wcf rest


    【解决方案1】:

    WCF 有很多 扩展点来做这样的事情。您可能追求的是实现IDispatchMessageInspector 的自定义行为。

    创建一个如下所示的类:

    public class MyCustomBehavior : IDispatchMessageInspector, IEndpointBehavior
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            //here you can work with request.Headers.
            return null;
        }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
        }
    
        //there are a bunch of other methods needed
        //but you can leave their implementations empty.
        //...
    }
    

    然后,您可以在打开服务之前以编程方式将自定义行为添加到服务端点:

    host.Description.Endpoints[0].Behaviors.Add(new WcfService2.MyCustomBehavior());
    

    Paolo Pialorsi 有一个 good tutorial,负责编写消息检查器。

    【讨论】:

    • 标头在 Message 类中是只读的。公共抽象 MessageHeaders 标头 { 获取; }.
    • 是的,Headers 是 get-only,但您仍然可以调用 Headers.Add(...) 来修改集合。
    【解决方案2】:

    你看过http://wcf.codeplex.com吗?新的HTTP堆栈有一个流水线模型,可以让你做各种各样的事情。

    【讨论】:

    • 我还不能使用它,因为它处于预览状态。我正在使用较旧的 REST 入门套件。请求标头是只读的。公共密封类 HttpRequestMessageProperty { ... public WebHeaderCollection Headers { get; } ... }
    • @amit_g REST 入门工具包上的许可证基本上会阻止您在 MS 发布真实版本后使用它。对于服务器端的东西,真实版本在 .Net 4 中,因此许可证不再有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    相关资源
    最近更新 更多