我有一个基于 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 应用程序中创建 WebHttpBinding
后 binding.Security.Transport
为 null(它不是 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/