2011-01-21 189 views
0

使用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()); 

保羅Pialorsi有good tutorial其涉及編寫信息檢查員。

+0

標題在Message類中是隻讀的。公共抽象MessageHeaders標題{get; }。 – 2011-01-21 17:32:24

+0

是的,`Headers`是隻讀的,但你仍然可以調用`Headers.Add(...)`來修改集合。 – 2011-01-22 06:15:21

1

你看過http://wcf.codeplex.com新的HTTP協議棧有一個流水線模型,它允許你做所有類似的事情。