【问题标题】:Add authentication token into WCF service call using channel factory使用通道工厂将身份验证令牌添加到 WCF 服务调用中
【发布时间】:2019-10-31 06:57:45
【问题描述】:

我使用以下内容创建了我的频道工厂。

var client = GetMyChannelFactory<MyService>();
var myService = client.CreateChannel();
//Add token before this as following method cannot be called by anonymous
var result = myService.GetResult();


internal ChannelFactory<T> GetFirmChannelFactory<T>()
{
    BasicHttpBinding basicHttpBinding = GetBasicHttpBinding();
    string url = "example.com";
    EndpointAddress address = new EndpointAddress(url);
    return new ChannelFactory<T>(basicHttpBinding, address);
}

我有以下标记要添加到我正在调用的 WCF 请求的标头中。

var token = applicationUser.Token.Result;

我尝试添加 EndPoint 行为但没有成功。

如何将授权持有者令牌添加到 WCF 请求标头中?

【问题讨论】:

    标签: c# wcf http-headers bearer-token channelfactory


    【解决方案1】:

    您似乎想在特定请求中添加自定义 Http-headers。添加 HTTP 标头通常有两种方法。

    Uri uri = new Uri("http://10.157.13.69:16666");
                BasicHttpBinding binding = new BasicHttpBinding();
                ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>(binding, new EndpointAddress(uri));
                ITestService service = factory.CreateChannel();
                using (new OperationContextScope((IClientChannel)service))
                {
                    //first method to add HTTP header.
                    //HttpRequestMessageProperty request = new HttpRequestMessageProperty();
                    //request.Headers["MyHttpheader"] = "myvalue";
                    //OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;
                    OperationContext oc = OperationContext.Current;
                    WebOperationContext woc = new WebOperationContext(oc);
                    woc.OutgoingRequest.Headers.Add("myhttpheader", "myvalue");
                    //invocation, only valid in this request.
                    var result = service.GetResult();
                    Console.WriteLine(result);
                }
    

    结果。

    我们需要注意的是,请求以及特定的 Http Header 仅在 OperationContextScope 内有效。释放 OperationContextScope 后,I.E. OperationContextScope 之外的调用未附加特定的 Http Header。
    如果我们想在每个请求中添加一个持久的 HTTP 标头,我们可以考虑使用下面的接口。
    How to add a custom HTTP header to every WCF call?
    如果有什么可以帮助的,请随时告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2018-03-28
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      相关资源
      最近更新 更多