使用System.ServiceModel

时间:2015-11-27 08:08:15

标签: c# android wcf rest xamarin

我通过HTTPS启用RESTful服务并启用了基本身份验证。我可以使用“普通”Windows控制台应用程序中的以下代码来使用它:

        var uri = "https://example.com/service";
        var binding = new WebHttpBinding();
        binding.Security.Transport = new HttpTransportSecurity();
        binding.Security.Mode = WebHttpSecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
        var factory = new ChannelFactory<IService>(binding, uri);
        factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
        factory.Credentials.UserName.UserName = "user";
        factory.Credentials.UserName.Password = "password";
        factory.Open();
        IService service = factory.CreateChannel();
        service.SomeMethod();

但是当我在Xamarin Android应用程序中使用完全相同的代码时,我会收到WebException:

  

处理网络请求时出错:状态代码401(未经授权):未经授权

我是Xamarin的新手,但据我所知,ServiceModel实现与Silverlight中的相同。

请帮助mi解决这个问题。

1 个答案:

答案 0 :(得分:1)

显然使用此API无法完成。这就是为什么在Xamarin / Android应用程序中创建binding.Security.TransportWebHttpBinding null (在“普通”控制台应用程序中它不是 null )。< / p>

解决方案是使用低级HttpWebRequest

    public void GetDataFromRestService()
    {
        var request = HttpWebRequest.Create("https://example.com/service/SomeMethod");
        SetBasicAuthHeader(request, "user", "password");

        request.ContentType = "application/json";
        request.Method = "GET";

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.Out.WriteLine("ERROR: Server status code: {0}", response.StatusCode);
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                var content = reader.ReadToEnd();
                if (string.IsNullOrWhiteSpace(content))
                {
                    Console.Out.WriteLine("ERROR: Empty response.");
                }
                else
                {
                    Console.Out.WriteLine("Response: {0}", content);
                }
            }
        }
    }

    public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic " + authInfo;
    }

之后我们需要手动解析返回的JSON内容(Xsonrin有Json.NET)。或者我们可以使用像RestSharp这样的库,它也可以用于Xamarin并使事情变得更容易。