HttpClient不能在Xamarin中多次发送相同的请求

本文关键字:请求 不能 Xamarin HttpClient | 更新日期: 2023-09-27 18:26:34

我有一个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);
}

HttpClient不能在Xamarin中多次发送相同的请求

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

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