英文:
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

but I get this Exception:

This is the base of the controller which makes the 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}");
    }
答案1
得分: 0
明显地,我在Maui中需要以不同的方式进行DI,因此在SetHeaders()方法的运行时_caching为null。
编辑:
此刻,我已经在一个扩展方法中实现了DI,使用以下方式:
MauiAppBuilder.Services.AddSingleton<T>();
并在构造函数中获取它,而不是在类中使用:
Dependencyservice.Get<T>()。
英文:
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<T>();
and getting it in the constructor
instead of using
Dependencyservice.Get<T>()
in the class
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论