简体   繁体   中英

Consume WCF REST basic auth service in Xamarin using System.ServiceModel

I have a RESTful service over HTTPS with basic authentication enabled. I can consume it using below code in "normal" Windows Console application:

        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();

But when I use exactly the same code in the Xamarin Android app I receive WebException:

There was an error on processing web request: Status code 401(Unauthorized): Unauthorized

I'm new to the Xamarin, but as far as I know the ServiceModel implementation is the same as in the Silverlight.

Please help mi solve this problem.

Apparently it cannot be done using this API. That is why binding.Security.Transport is null after creating WebHttpBinding in Xamarin/Android app (it is not null in "normal" console application).

The solution is to use low level 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;
    }

After that we need to manually parse returned JSON content (there is Json.NET for Xamarin). Or we can use some library like RestSharp that is also avaiable for Xamarin and makes things easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM