Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用HttpWebRequest连接Azure服务总线中继(WCF端点)_C#_Wcf_Rest_Azure_Azureservicebus - Fatal编程技术网

C# 使用HttpWebRequest连接Azure服务总线中继(WCF端点)

C# 使用HttpWebRequest连接Azure服务总线中继(WCF端点),c#,wcf,rest,azure,azureservicebus,C#,Wcf,Rest,Azure,Azureservicebus,请帮忙。我试图使用HttpWebRequest访问暴露于服务总线中继端点的WCF服务 我通过OAuth WRAP协议成功地从ACS获得了一个令牌。使用该令牌作为请求头中的授权,我创建了一个WebRequest来与WCF服务通信,端点配置为WebHttpRelayBinding,WCF服务方法应用了OperationContractAttribute和WebGetAttribute 运行客户端应用程序时,出现以下错误: 这封信是写给你的 '' 由于AddressFilter不匹配,无法在接收器上处

请帮忙。我试图使用HttpWebRequest访问暴露于服务总线中继端点的WCF服务

我通过OAuth WRAP协议成功地从ACS获得了一个令牌。使用该令牌作为请求头中的授权,我创建了一个WebRequest来与WCF服务通信,端点配置为WebHttpRelayBinding,WCF服务方法应用了OperationContractAttribute和WebGetAttribute

运行客户端应用程序时,出现以下错误:

这封信是写给你的 '' 由于AddressFilter不匹配,无法在接收器上处理 在端点调度器。检查发送方和接收方的 我同意

我在谷歌上搜索到一个建议,建议将以下属性应用于服务类:

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
虽然这解决了以前的错误,但现在客户端应用程序出现以下错误:

由于以下原因,无法在接收方处理操作为“GET”的消息 在EndpointDispatcher上创建不匹配的ContractFilter。这可能是 因为合同不匹配(双方的操作不匹配 发送方和接收方)或发送方之间的绑定/安全不匹配 还有听筒。检查发送方和接收方是否具有相同的 合同和相同的约束(包括安全要求,例如。 消息、传输、无)

我想我在WCF服务方面遗漏了一些东西。共享客户端代码和服务代码以供审阅

WCF服务代码:

[ServiceContract]
interface IStudentInfo
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/GetStudentInfo/{studentId}")]
    string GetStudentInfo(string studentId);
}

        [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
        private class StudentInfo : IStudentInfo
        {
            string IStudentInfo.GetStudentInfo(string studentId)
            {
                string returnString = null;

                // .....

                return returnString;
            }
        }

        public void Run()
        {
            Console.WriteLine("LISTENER");
            Console.WriteLine("========");

            string serviceNamespace = "namespace";
            string issuerName = "owner";
            string issuerKey = "key";
            string servicePath = "Student/GetInfo";

            ServiceHost sh = new ServiceHost(typeof(StudentInfo));

            // Binding
            WebHttpRelayBinding binding2 = new WebHttpRelayBinding();

            Uri uri = ServiceBusEnvironment.CreateServiceUri(Uri.UriSchemeHttps, serviceNamespace, servicePath);
            Console.WriteLine("Service Uri: " + uri);
            Console.WriteLine();

            sh.AddServiceEndpoint(typeof(IStudentInfo), binding2, uri);

            // Create the ServiceRegistrySettings behavior for the endpoint.
            var serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            // Create the shared secret credentials object for the endpoint matching the 
            // Azure access control services issuer 
            var sharedSecretServiceBusCredential = new TransportClientEndpointBehavior()
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey)
            };

            // Add the service bus credentials to all endpoints specified in configuration.
            foreach (var endpoint in sh.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            sh.Open();

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();

            sh.Close();
        }
    static void Main(string[] args)
    {
        var studentId = "1";

        string _token = GetToken();
        Console.WriteLine(_token);

        // Create and configure the Request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://namespace.servicebus.windows.net/Student/GetInfo/GetStudentInfo/" + studentId);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "GET";
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("WRAP access_token=\"{0}\"", _token));

        // Get the response using the Request
        HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;

        // Read the stream from the response object
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);

        // Read the result from the stream reader
        string result = reader.ReadToEnd();

        Console.WriteLine("Result: " + result);

        Console.ReadLine();
    }

    static string GetToken()
    {
        string base_address = string.Format("https://namespace-sb.accesscontrol.windows.net");
        string wrap_name = "owner";
        string wrap_password = "key";
        string wrap_scope = "http://namespace.servicebus.windows.net/";

        WebClient client = new WebClient();
        client.BaseAddress = base_address;

        NameValueCollection values = new NameValueCollection();
        values.Add("wrap_name", wrap_name);
        values.Add("wrap_password", wrap_password);
        values.Add("wrap_scope", wrap_scope);

        byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
        string response = Encoding.UTF8.GetString(responseBytes);

        string token = response.Split('&')
         .Single(value => value.StartsWith("wrap_access_token="))
         .Split('=')[1];

        string _token = HttpUtility.UrlDecode(token);

        return _token;
    }
服务消费代码:

[ServiceContract]
interface IStudentInfo
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/GetStudentInfo/{studentId}")]
    string GetStudentInfo(string studentId);
}

        [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
        private class StudentInfo : IStudentInfo
        {
            string IStudentInfo.GetStudentInfo(string studentId)
            {
                string returnString = null;

                // .....

                return returnString;
            }
        }

        public void Run()
        {
            Console.WriteLine("LISTENER");
            Console.WriteLine("========");

            string serviceNamespace = "namespace";
            string issuerName = "owner";
            string issuerKey = "key";
            string servicePath = "Student/GetInfo";

            ServiceHost sh = new ServiceHost(typeof(StudentInfo));

            // Binding
            WebHttpRelayBinding binding2 = new WebHttpRelayBinding();

            Uri uri = ServiceBusEnvironment.CreateServiceUri(Uri.UriSchemeHttps, serviceNamespace, servicePath);
            Console.WriteLine("Service Uri: " + uri);
            Console.WriteLine();

            sh.AddServiceEndpoint(typeof(IStudentInfo), binding2, uri);

            // Create the ServiceRegistrySettings behavior for the endpoint.
            var serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            // Create the shared secret credentials object for the endpoint matching the 
            // Azure access control services issuer 
            var sharedSecretServiceBusCredential = new TransportClientEndpointBehavior()
            {
                TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey)
            };

            // Add the service bus credentials to all endpoints specified in configuration.
            foreach (var endpoint in sh.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }

            sh.Open();

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();

            sh.Close();
        }
    static void Main(string[] args)
    {
        var studentId = "1";

        string _token = GetToken();
        Console.WriteLine(_token);

        // Create and configure the Request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://namespace.servicebus.windows.net/Student/GetInfo/GetStudentInfo/" + studentId);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "GET";
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("WRAP access_token=\"{0}\"", _token));

        // Get the response using the Request
        HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;

        // Read the stream from the response object
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);

        // Read the result from the stream reader
        string result = reader.ReadToEnd();

        Console.WriteLine("Result: " + result);

        Console.ReadLine();
    }

    static string GetToken()
    {
        string base_address = string.Format("https://namespace-sb.accesscontrol.windows.net");
        string wrap_name = "owner";
        string wrap_password = "key";
        string wrap_scope = "http://namespace.servicebus.windows.net/";

        WebClient client = new WebClient();
        client.BaseAddress = base_address;

        NameValueCollection values = new NameValueCollection();
        values.Add("wrap_name", wrap_name);
        values.Add("wrap_password", wrap_password);
        values.Add("wrap_scope", wrap_scope);

        byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
        string response = Encoding.UTF8.GetString(responseBytes);

        string token = response.Split('&')
         .Single(value => value.StartsWith("wrap_access_token="))
         .Split('=')[1];

        string _token = HttpUtility.UrlDecode(token);

        return _token;
    }
终于完成了

我缺少端点的
WebHttpBehavior
,该端点是将WCF服务公开为REST端点所必需的

endpoint.Behaviors.Add(new WebHttpBehavior());
或者,我也可以在
WebServiceHost
中托管服务,而不是“ServiceHost”,以使REST绑定能够工作

WebServiceHost sh = new WebServiceHost(typeof(StudentInfo));