我如何添加HTTP请求头到Silverlight RIA请求



我需要为每一个RIA服务请求传递一个HTTP头从Silverlight应用程序。头的值需要来自应用程序实例,而不是来自cookie。我知道这可以通过将其放在dto中来完成,但这不是一个选择,因为我们的许多服务调用使用实体和更改集,所以没有可以绑定到所有请求的基类。所以我正在寻找一个集中和安全的手段来传递一些东西与每个请求,所以开发人员不必担心它。自定义HTTP头会工作得很好,但我不知道如何拦截出站请求来设置它。

谁有什么主意我可以试试?

在较低的级别上,您可以在IClientMessageInspector的帮助下添加HTTP标头。试着从SL论坛的这篇文章开始。

下一步取决于你的用例。

如果标题的值对于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;
  }
}

最新更新