HttpClient对象在Xamarin.iOS上第二次不起作用

问题描述

我将HttpClient对象用于PostAsync。创建HttpClient对象时,我需要为iOS添加BackgroundSessionConfiguration。所以我这样修改代码

var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("my.app.identifier");
_client = new HttpClient (new NSUrlSessionHandler (configuration));

当我使用PostAsync发送第一个请求时,此方法有效。但是当我第二次发送请求时,它不起作用。

我是这样进行登录操作的:(它第一次起作用,但是如果我注销并再次登录,则不起作用。)

public class LoginService
    {
        private HttpClient _client;

        public LoginService()
        {
            if (_client == null)
                {
                    _client = Helper.CreateHttpClientLogin(_client);
                }
        }

    public async Task<LoginResponse<LoginDataResponse>> Login(LoginRequest request)
        {
            LoginResponse<LoginDataResponse> responseModel = new LoginResponse<LoginDataResponse>();
            try
            {
                string json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json,Encoding.UTF8,"application/json");

                var jsonBody = await _client.PostAsync(App.ServiceURL.Login_Url,content);
                string jsonstr = await jsonBody.Content.ReadAsstringAsync();

                if (jsonstr == null || jsonstr == "")
                {
                    responseModel.Success = false;
                    responseModel.Status = 0;
                    responseModel.Message = AppResources.UnkNownHostException;
                }
                else
                    responseModel = (LoginResponse<LoginDataResponse>)JsonConvert.DeserializeObject(jsonstr,typeof(LoginResponse<LoginDataResponse>));
            }
            catch (Exception ex)
            {
                string text = ex.ToString();
                responseModel.Status = 0;
                AppResources.Culture = CrossMultilingual.Current.CurrentCultureInfo;
                responseModel.Message = AppResources.UnkNownHostException;
            }
            return responseModel;
        }
}

public class Helper
{
    public static HttpClient CreateHttpClientLogin(HttpClient _client)
    {
            if (Device.RuntimePlatform == Device.iOS)
                {
                    var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("my.app.identifier");
                    _client = new HttpClient(new NSUrlSessionHandler(configuration));
                }
                else
                {
                    //_client = new HttpClient(new System.Net.Http.httpclienthandler());
                    httpclienthandler handler = new httpclienthandler();
                    handler.ServerCertificateCustomValidationCallback = (message,cert,chain,errors) => true;
                    _client = new HttpClient(handler);
                }

            return _client;
        }
}

我在AppDelegate上有以下代码:(我不知道,但可能会导致错误

public static Action BackgroundSessionCompletionHandler;
public override void HandleEventsForBackgroundUrl(UIApplication application,string sessionIdentifier,Action completionHandler)
{
    // We get a completion handler which we are supposed to call if our transfer is done.
    BackgroundSessionCompletionHandler = completionHandler;
}

我该怎么办?

编辑:

我通过在首次打开应用程序后创建“登录服务”对象解决了上面提到的问题。 (以前注销后,每次登录时我都在重建)

但是现在我还有其他错误。当我在“ iPhone 7 plus-iOS 13.6”设备上运行我的应用程序时,出现此错误

System.Net.Http.HttpRequestException: unkNown error ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1 "unkNown error" UserInfo={NSErrorFailingURLStringKey=https://mydomain/Api/Login,NSErrorFailingURLKey=https://mydomain/Api/Login,_NSURLErrorRelatedURLSessionTaskErrorKey=(
    "BackgroundDataTask <E69F3EAF-0AE9-4FAE-A01B-988167B7F6BC>.<3>"
),_NSURLErrorFailingURLSessionTaskErrorKey=BackgroundDataTask <E69F3EAF-0AE9-4FAE-A01B-988167B7F6BC>.<3>,NSLocalizedDescription=unkNown error}
   --- End of inner exception stack trace ---
  at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) [0x001d4] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/Foundation/NSUrlSessionHandler.cs:527 
  at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask,System.Net.Http.HttpRequestMessage request,System.Threading.CancellationTokenSource cts,System.Boolean disposeCts) [0x0017e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506 
  at App.Services.LoginService.Login (FileOrbis.Models.RequestModels.LoginRequest request) [0x00084] in C:\Users\PcName\Desktop\App\App\Services\LoginService.cs:40

模拟器日志文件为:

Startup:
    arguments: --device=06098E5B-1853-4A83-8434-8071D8973A14 --launchsim=//Users/deytek/Library/Caches/Xamarin/mtbs/builds/App.iOS/b2c75f2acbd4ff91c305dba10ca791b7/bin/iPhonesimulator/Debug/App.iOS.app -argument=-monodevelop-port -argument=51890 -setenv=__XAMARIN_DEBUG_PORT__=51890 --sdkroot=/Applications/Xcode.app -h=192.168.1.7 -ssh=deytek --launched-by=devenv-16.0 
    version: 16.7.0.0 (54a29526ef6f853bdd37adbcc3791ce90ca82735)
Connecting to existing client
Exit:
    Exit Code: 0

使用后台会话配置时遇到此错误。如果我使用普通的HttpClient对象(没有后台会话配置),它将起作用

注意:我还尝试了iPhone 5s iOS 12.4.8和iPad Pro(第三代)iOS 13.6.1。这些设备都可以使用。但它不适用于iPhone 7 Plus 13.6

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...