C# HttpClient无法在Xamarin中多次发送相同的请求
我有一个Xamarin多平台应用程序,需要有人登录我的应用程序。要检查凭据,我有一个API。但我为调用API而创建的代码给了我以下错误: System.InvalidOperationException:无法发送相同的请求消息 多次 通过以下代码单击按钮调用该代码:C# HttpClient无法在Xamarin中多次发送相同的请求,c#,xamarin,mono,C#,Xamarin,Mono,我有一个Xamarin多平台应用程序,需要有人登录我的应用程序。要检查凭据,我有一个API。但我为调用API而创建的代码给了我以下错误: System.InvalidOperationException:无法发送相同的请求消息 多次 通过以下代码单击按钮调用该代码: Models.LoginModel login = new Models.LoginModel(); login.Login = username.Text; login.Wachtwoord = passw
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);
}
正如我在评论中提到的,您可能需要删除行
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;
}
您还可以提供APIREST类中Post方法的代码吗?在我看来,GetResponse
方法的返回值似乎有问题。在第var resp=response.Content.ReadAsStringAsync()行中读取结果代码>但只需返回响应消息即可。我猜您在apirest.Post
方法中也会执行类似的操作,该方法将失败,因为在运行response.Content.ReadAsStringAsync
方法调用response
对象后,该对象将被释放。
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;
}