.NET MAUI安卓端POST带请求内容时抛出System.ObjectDisposedException异常
.NET MAUI Android平台POST带内容请求抛出
System.ObjectDisposedException异常 问题详情
开发.NET MAUI应用时,带内容的POST请求函数在Windows平台运行正常,但在Android平台执行时抛出异常:System.ObjectDisposedException: Cannot access a closed Stream。
其中GET、DELETE请求在双平台均能正常运行,不带内容的POST请求(示例代码如下)也可在双平台正常工作,仅带内容的POST请求在Android平台报错。
相关代码
带内容的POST请求代码
public async static Task InsertParts(IEnumerable<PartDTO> partsToReport) { using (HttpClient client = GetClient()) { AddAuthorizationHeader(client); string url = $"{Url}/endpoint"; string jsonData = JsonSerializer.Serialize(partsToReport); HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); if (!(response.IsSuccessStatusCode)) { throw new Exception($"Failed to insert parts: {response.ReasonPhrase}"); } } }
HttpClient创建代码
public static HttpClient GetClient() { #if DEBUG HttpClientHandler insecureHandler = new HttpClientHandler(); insecureHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; return new HttpClient(insecureHandler); #else return new HttpClient(); #endif }
正常运行的无内容POST请求示例
HttpResponseMessage response = await client.PostAsync($"{Url}/inventory/{id}/{destination}", null);
解决方案
复用HttpClient实例:Android平台下频繁创建并销毁HttpClient可能导致请求流被提前关闭。将HttpClient改为静态单例,避免每次请求都创建新实例:
private static HttpClient _httpClient; public static HttpClient GetClient() { if (_httpClient == null) { #if DEBUG HttpClientHandler insecureHandler = new HttpClientHandler(); insecureHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; _httpClient = new HttpClient(insecureHandler); #else _httpClient = new HttpClient(); #endif } return _httpClient; }同时移除
InsertParts方法中的using块,改为直接使用单例HttpClient。显式管理HttpContent生命周期:将
StringContent放入using块中,确保其生命周期覆盖整个请求过程:string jsonData = JsonSerializer.Serialize(partsToReport); using (var content = new StringContent(jsonData, Encoding.UTF8, "application/json")) { var response = await client.PostAsync(url, content).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new Exception($"Failed to insert parts: {response.ReasonPhrase}"); } }添加
ConfigureAwait(false):避免Android平台的同步上下文切换导致流被提前释放,在异步调用后添加该配置:var response = await client.PostAsync(url, content).ConfigureAwait(false);
内容的提问来源于stack exchange,提问作者Dragon Slayer
相关产品推荐
相关产品推荐

