HttpClient 无法在 Xamarin 中多次发送相同的请求

HttpClient cannot send the same request multiple times in Xamarin

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

System.InvalidOperationException: Cannot send the same request message multiple times

    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);
}

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

ReadAsStringAsync() 方法将处理 HttpResponseMessage class 的实例,使其不再有效。由于您没有 return 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;
}