xamarin web API身份验证

时间:2016-05-03 15:31:50

标签: authentication login xamarin mvvmcross

我是Xamarin和移动开发的新手,我目前正在开发一个带有身份验证的示例应用程序。我们正在使用我们的内部Web API服务进行身份验证,有人可以指导我如何继续这种情况。我打算在我的开发中使用MvvmCross框架。我没有使用Xamarin表单并使用Android平台特定项目作为我初始开发的一部分。任何帮助真的很感激。

以下是我用来调用我的WebAPI的示例代码

public async Task<HttpResponseMessage> PutAsync<T>(string url,T content)
        {

             using (var client = new HttpClient(new NativeMessageHandler()))
          //  using (var client = new HttpClient())
            {
                string json = JsonConvert.SerializeObject(content);
                var address = string.Format("{0}{1}", WebService.BaseUrl, url);
                var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PutAsync(new System.Uri(address), httpContent);
                return response;
            }
        }`enter code here`
  

我能够使用http调用示例获取请求但是

失败      
    

HTTPS

  

请求。我正在测试android 4.4 Kit kat设备

System.Net.Http.HttpMessageHandler handler = new NativeMessageHandler(false,true);

.Net.Http.HttpClient client = (handler == null) ? new System.Net.Http.HttpClient() :new System.Net.Http.HttpClient(new NativeMessageHandler(false,true));
result = client.GetAsync("https://httpbin.org/ip");
                var stream = await result.Result.Content.ReadAsStringAsync();

2 个答案:

答案 0 :(得分:3)

如果您的服务支持OAuth(我建议用于应用),您可以使用Xamarin.Auth库对用户进行身份验证。 https://www.nuget.org/packages/Xamarin.Auth/

以下是如何使用它的教程:https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/

答案 1 :(得分:0)

我发布了我的代码,我认为它有效。

using System.Threading.Tasks;
using Newtonsoft.Json;
using ModernHttpClient;
using System.Net.Http;
using System.Text;
namespace App.Portable
{
    public interface IHttpService
    {
        Task<T> ReadContentAsync<T>(Task<HttpResponseMessage> response);
        Task<HttpResponseMessage> GetAsync(string url);
        Task<string> PutAsync<T>(string url,T content);
    }

    public class HttpService : IHttpService
    {

        public async Task<HttpResponseMessage> GetAsync(string url)
        {
            throw new HttpRequestException();
        }
        public async Task<string> PutAsync<T>(string url,T content)
        {
            HttpMessageHandler handler = new NativeMessageHandler(false,true);
            HttpClient client = (handler == null) ? new HttpClient() :new HttpClient(new NativeMessageHandler(false,true));
                string json = JsonConvert.SerializeObject(content);
                var address = string.Format("{0}{1}", WebService.BaseUrl, url);
                var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                var response =  client.PutAsync(new System.Uri(address), httpContent);
                var stream = await response.Result.Content.ReadAsStringAsync();
            return stream;

        }
    }
}
相关问题