HttpClient无法在Xamarin

时间:2015-12-11 11:50:17

标签: c# xamarin mono

我有一个Xamarin多平台应用程序,我需要人们登录我的应用程序。要检查凭据,我有一个API。但是我为调用API而创建的代码给出了以下错误:

  

System.InvalidOperationException:无法发送相同的请求消息   多次

    private HttpResponseMessage GetResponse(HttpMethod method, string requestUri, object value)
    {
        HttpRequestMessage message = new HttpRequestMessage(method, requestUri);

        if (Login != null)
        {
            message.Headers.Add("Authorization", "Basic " + Login.AuthenticatieString);
        }

        if (value != null)
        {
            string jsonString = JsonConvert.SerializeObject(value);
            HttpContent content = new StringContent(jsonString);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            message.Content = content;
        }

#if DEBUG
        ServicePointManager.ServerCertificateValidationCallback =
delegate (object s, X509Certificate certificate,
         X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
#endif
        HttpResponseMessage response = Client.SendAsync(message).Result;

        var resp = response.Content.ReadAsStringAsync();
        return response;
    }

通过以下代码点击按钮调用该代码:

    Models.LoginModel login = new Models.LoginModel();
    login.Login = username.Text;
    login.Wachtwoord = password.Text;

    var result = new ApiRequest()
                .Post("api/login", login);

如果我在发生错误的行上设置断点

HttpResponseMessage response = Client.SendAsync(message).Result;

我可以看到它只执行一次。

更新1: .Post函数只需调用GetResponse方法,如下所示:

public HttpResponseMessage Put(string requestUri, object value)
{
    return GetResponse(HttpMethod.Put, requestUri, value);
}

1 个答案:

答案 0 :(得分:2)

正如我的评论中所提到的,您可能需要从var resp = response.Content.ReadAsStringAsync();方法中删除行GetResponse(...)

ReadAsStringAsync()方法将处置HttpResponseMessage类的实例,使其不再有效。由于您没有返回resp变量,而是(此时已经处置)response变量,我稍后会假设您在代码中的某个位置再次调用此对象。这将导致InvalidOperationException被抛出。

所以尝试使用以下功能:

private HttpResponseMessage GetResponse(HttpMethod method, string requestUri, object value)
{
    HttpRequestMessage message = new HttpRequestMessage(method, requestUri);

    if (Login != null)
    {
        message.Headers.Add("Authorization", "Basic " + Login.AuthenticatieString);
    }

    if (value != null)
    {
        string jsonString = JsonConvert.SerializeObject(value);
        HttpContent content = new StringContent(jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        message.Content = content;
    }

    #if DEBUG
    ServicePointManager.ServerCertificateValidationCallback =
     delegate (object s, X509Certificate certificate,
     X509Chain chain, SslPolicyErrors sslPolicyErrors)
     { return true; };
    #endif

    HttpResponseMessage response = Client.SendAsync(message).Result;

    return response;
}