2011-12-08 138 views
1

我需要为每个从Silverlight应用程序创建的每个RIA服务请求传递一个HTTP标头。标题的值需要来自应用实例,而不是来自cookie。我知道这可以通过将它放在DTO中来实现,但这不是一种选择,因为我们的许多服务调用使用实体和更改集合,所以没有基类可以适用于所有请求。所以我正在寻找一种集中和安全的方式来将每个请求传递回去,以便开发人员不必担心。自定义HTTP标头可以正常工作,但我不知道如何拦截出站请求来设置它。如何将HTTP请求标题添加到Silverlight RIA请求

任何人有任何想法,我可以尝试?

回答

3

在较低级别上,您可以在IClientMessageInspector的帮助下添加HTTP标头。尝试从this post on SL forum开始。

下一步取决于您的使用情况。

如果头部的值必须与DomainContext调用的任何方法相同,那么您可以使用partial类扩展上下文,为头部值添加属性并在检查器中使用该属性。

如果您需要为每个方法调用传递不同的值,您可能需要将您的DomainContext包装到另一个类中,并为上下文的每个方法添加一个参数,以接受标头值并将其传递给检查员莫名其妙。不用说,没有代码生成器,这将是困难的。

下面是来自SL论坛第一种情况的调整采样:我需要

public sealed partial class MyDomainContext 
{ 
    public string HeaderValue { get; set; } 

    partial void OnCreated() 
    { 
    WebDomainClient<IMyDomainServiceContract> webDomainClient = (WebDomainClient<IMyDomainServiceContract>)DomainClient; 
    CustomHeaderEndpointBehavior customHeaderEndpointBehavior = new CustomHeaderEndpointBehavior(this); 
    webDomainClient.ChannelFactory.Endpoint.Behaviors.Add(customHeaderEndpointBehavior); 
    } 
} 

public class CustomHeaderEndpointBehavior : IEndpointBehavior 
{ 
    MyDomainContext _Ctx; 

    public CustomHeaderEndpointBehavior(MyDomainContext ctx) 
    { 
    this._Ctx = ctx; 
    }  

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } 
    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 
    { 
    clientRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(this._Ctx)); 
    } 
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) { } 
    public void Validate(ServiceEndpoint endpoint) { } 
} 

public class CustomHeaderMessageInspector : IClientMessageInspector 
{ 
    MyDomainContext _Ctx; 

    public CustomHeaderMessageInspector(MyDomainContext ctx) 
    { 
    this._Ctx = ctx; 
    } 

    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) {} 
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel) 
    { 
    string myHeaderName = "X-Foo-Bar"; 
    string myheaderValue = this._Ctx.HeaderValue; 

    HttpRequestMessageProperty property = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; 
    property.Headers[myHeaderName] = myheaderValue; 
    return null; 
    } 
} 
+0

究竟是什么。事实上,我应该知道自从我使用WCF扩展点在服务器上做类似的事情。感谢Pavel !. –