升级 Xamarin 到 Maui 项目时,在执行 HttpClient.GetAsync 时抛出 NullReference 异常。

huangapple go评论63阅读模式
英文:

Upgraded Xamarin to Maui Project Throws NullReference Exception While Executing HttpClient.GetAsync

问题

我最近将我的Xamarin项目升级到Maui,现在在我的HttpClient的Get请求中遇到了空引用异常,但找不到问题所在。

我的HttpClient填充正确,我像下面所示调用它:

但我收到了这个异常:

这是创建HttpClient的控制器的基础部分:

public BaseControllerService()
{
    //GetUrl();
    AuthorisationRetry = Policy
        .HandleResult<HttpResponseMessage>(resp => resp.StatusCode == HttpStatusCode.Unauthorized)
        .RetryAsync(1, async (_, retryCount) =>
        {
            var answer = await CallRefreshToken();
            if (answer is {IsSuccess: true}) return;
            await _caching.DeleteTokensAsync();
            await Shell.Current.Navigation.PopToRootAsync();
            await Shell.Current.GoToAsync("//LoginPage");
        });
    var test = AppSettings.Url.Value;
    _cookieContainer = new CookieContainer();
    var handler = new HttpClientHandler {CookieContainer = _cookieContainer};
    _httpClient = new HttpClient(handler)
    {
        BaseAddress = new Uri(AppSettings.Url.Value ?? throw new NullReferenceException("AppSettings Url is null"))
    };
    SetHeaders();
}

protected async void SetHeaders()
{
    _httpClient.DefaultRequestHeaders.Clear();

    var temp = await _caching.GetUserTokenAsync();
    if (!string.IsNullOrEmpty(temp)) _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {temp}");
}
英文:

I recently upgraded my Xamarin project to Maui and now I get a nullrefference during a GetRequest in my HttpClient but can't find where.

My HttpClient is filled in correctly and I call it like shown below
升级 Xamarin 到 Maui 项目时,在执行 HttpClient.GetAsync 时抛出 NullReference 异常。
but I get this Exception:
升级 Xamarin 到 Maui 项目时,在执行 HttpClient.GetAsync 时抛出 NullReference 异常。
This is the base of the controller which makes the HttpClient:

    public BaseControllerService()
    {
        //GetUrl();
        AuthorisationRetry = Policy
            .HandleResult&lt;HttpResponseMessage&gt;(resp =&gt; resp.StatusCode == HttpStatusCode.Unauthorized)
            .RetryAsync(1, async (_, retryCount) =&gt;
            {
                var answer = await CallRefreshToken();
                if (answer is {IsSuccess: true}) return;
                await _caching.DeleteTokensAsync();
                await Shell.Current.Navigation.PopToRootAsync();
                await Shell.Current.GoToAsync(&quot;//LoginPage&quot;);
            });
        var test = AppSettings.Url.Value;
        _cookieContainer = new CookieContainer();
        var handler = new HttpClientHandler {CookieContainer = _cookieContainer};
            _httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(AppSettings.Url.Value ?? throw new NullReferenceException(&quot;AppSettings Url is null&quot;))
            };
        SetHeaders();
    }

    protected async void SetHeaders()
    {
        _httpClient.DefaultRequestHeaders.Clear();

        var temp = await _caching.GetUserTokenAsync();
        if (!string.IsNullOrEmpty(temp)) _httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, $&quot;Bearer {temp}&quot;);
    }

答案1

得分: 0

明显地,我在Maui中需要以不同的方式进行DI,因此在SetHeaders()方法的运行时_caching为null。

编辑:
此刻,我已经在一个扩展方法中实现了DI,使用以下方式:

MauiAppBuilder.Services.AddSingleton&lt;T&gt;();

并在构造函数中获取它,而不是在类中使用:

Dependencyservice.Get&lt;T&gt;()。
英文:

so apearently I have to do DI differently in Maui and thus during runtime _caching in the SetHeaders() was null

edit:
at this moment I have implemented DI in a extension method using

MauiAppBuilder.Services.AddSingleton&lt;T&gt;();

and getting it in the constructor
instead of using

Dependencyservice.Get&lt;T&gt;()

in the class

huangapple
  • 本文由 发表于 2023年6月1日 17:04:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定