【问题标题】:Adding an Authorization header to a Service Reference SOAP request将授权标头添加到服务引用 SOAP 请求
【发布时间】:2017-01-30 16:37:26
【问题描述】:

我已经使用了一个 WSDL,并成功调用了 Web 服务方法。请求有一个 Authorization 标头,只能在发出请求时添加:

    public static NumberCaptureClient Connect()
    {
        var remoteAddress = new EndpointAddress("https://website.com:8443/webservice/WebServiceNumberCapture");

        using (var NumberCaptureClient = new NumberCaptureClient(new BasicHttpBinding(BasicHttpSecurityMode.Transport), remoteAddress))
        {
            NumberCapture.ClientCredentials.UserName.UserName = "test";
            NumberCapture.ClientCredentials.UserName.Password = "test";

            try
            {
                using (OperationContextScope scope = new OperationContextScope(NumberCaptureClient.InnerChannel))
                {
                    var httpRequestProperty = new HttpRequestMessageProperty();

                    httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " +
                    Convert.ToBase64String(Encoding.ASCII.GetBytes(NumberCaptureClient.ClientCredentials.UserName.UserName + ":" + NumberCaptureClient.ClientCredentials.UserName.Password));

                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                }

            }
            catch (Exception error)
            {
                MessageBox.Show("Error");
                return null;
            }

            return NumberCaptureClient;
        }    
    }

如您所见,我需要返回代理客户端的实例(客户端有数百个方法都需要标头)但需要它,因此标头总是被发送,使用“使用”子句不可能,因为范围在它之外丢失。

有没有办法永久添加标头,以便将它们与对 Web 服务的每个请求一起发送?

【问题讨论】:

    标签: c# web-services


    【解决方案1】:

    这是一个 WCF 代理,对吧?一般来说,您应该从您的Connect 方法中删除using。如果该方法用于获取准备好的服务代理,那么将其作为创建它的方法的一部分进行处理是没有意义的。

    相反,使用Connect方法的方法/代码应该负责using它:

    using(var proxy = theClass.Connect()) 
    {
        // call service using proxy here
    
        // process response here, if you may need to call the service again
        // as part of processing
    }
    // process response here if you don't need to call the service again
    

    但是有一个问题,因为对于WCF 代理,Dispose 方法在内部调用了Close 方法,这反过来又会引发异常。出于这个原因,Microsoft 对如何处理 WCF 代理的清理提出了建议。见here

    【讨论】:

    • 谢谢,有一点隧道视野。现在完美运行。
    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2018-05-04
    相关资源
    最近更新 更多