c# - 使用 System.ServiceModel 在 Xamarin 中使用 WCF REST 基本身份验证服务

标签 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:

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

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

请帮助mi解决这个问题。

最佳答案

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

解决方案是使用低级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 内容(Xamarin 有 Json.NET)。或者我们可以使用像 RestSharp 这样的库这也适用于 Xamarin,让事情变得更容易。

关于c# - 使用 System.ServiceModel 在 Xamarin 中使用 WCF REST 基本身份验证服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952847/

相关文章:

c# - 将字符串从 AJAX 传递到后面的 ASP.NET C# 代码

c# - 将 JSON 数据发布到 WCF 服务时出现错误 415

wcf - 无法使用 https 调用 Azure 中托管的 WCF 服务的方法

android - Ember.js HTM5 的 UI 框架建议 => Phone Gap 应用程序(或替代堆栈)

c# - WCF SSL 负载均衡器。负载均衡器更改 ssl 端口

c# - 在 byte[] 中查找 byte[] 并在字符串中查找字符串的速度 - 为什么后者更快?

c# - 如何在不拆分单词的情况下将字符串拆分为List <string>?

c# - 没有调用 Windows 服务 OnStart 的原因可能是什么?

android - Android 动画是否会消耗更多的 CPU 资源?

android - float 操作按钮 layout_margin(Bottom) 对底部边距没有影响