检查API是否有效

时间:2018-07-16 13:11:34

标签: c# xamarin

我在Xamarin中工作,当前正在从API中获取一些数据,但是我不确定如何检查我是否真正通过了登录过程。我在登录过程中使用了以下代码:

public async Task<Token> Login(){
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("grant_type", 
    "password"));
    postData.Add(new KeyValuePair<string, string>("username", 
     "********"));
    postData.Add(new KeyValuePair<string, string>("password", 
    "********"));
    var content = new FormUrlEncodedContent(postData);
    var weburl = "**********************";
    var response = await PostResponse<Token>(weburl, content);
    DateTime dt = new DateTime();
    dt = DateTime.Today;
    response.Expire_Date = dt.AddSeconds(response.Expires_In);
    return response;
}

我试图通过对结果进行简单的toString方法来获得某种响应:

var result = App.RestService.Login();
string a = result.ToString();

当我写出a时,我只是遇到System.Threading.Tasks.Task [Interpret.InterpretedObject]错误,没什么可继续的。.

API应该给出errormsg以及一长串数字和字符的响应。

我想真正的问题是:如何从我的API中获取两条消息?

PS。 RestService的构造函数:

public RestService()
    {
        client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded' "));
    }

我更新了解决方案以解决异步问题,现在我得到了异常。

我这样调用异步方法:

public partial class DayView : ContentPage
{
    public DayView ()
    {
        InitializeComponent();
        getData();
    }

    public async void getData()
    {
        var result = await App.RestService.Login();
        string a = result.ToString();
        BindingContext = new Response(a);
    }
}

该应用程序现在可以在我的iPhone上运行,但是我得到了CertificateUnkown(TlsException),这是否意味着我已经开始与我的API进行首次联系?

1 个答案:

答案 0 :(得分:1)

您没有得到有意义的响应,因为Login是一个异步任务,您将其视为同步调用,而实际上应该等待它:

var result = await App.RestService.Login();