You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中Refit结合HttpFactory时DelegatingHandler失效问题

问题核心

你遇到的问题根源是**HttpLoggingHandler没注册到依赖注入(DI)容器里**。用AddHttpMessageHandler<HttpLoggingHandler>()时,框架会尝试从DI容器拿这个Handler的实例,要是没注册,就会抛出服务解析失败的异常,连带着依赖该HttpClient的ILoginService初始化失败,最终导致MainPage解析出错。

解决步骤

按下面两步操作就能修复:

  1. 先把HttpLoggingHandler注册到DI容器
    在调用AddRefitClient之前,把HttpLoggingHandler注册进去(推荐用Transient生命周期,因为这类Handler一般轻量无状态):

    builder.Services.AddTransient<HttpLoggingHandler>();
    
  2. 保留原有的Refit配置
    你原来的Refit客户端配置不用改,现在DI能正确解析HttpLoggingHandler并把它加入到HttpClient的消息处理管道里:

    builder.Services.AddRefitClient<ILoginService>()
        .ConfigureHttpClient(c => c.BaseAddress = new Uri("myUri"))
        .AddHttpMessageHandler<HttpLoggingHandler>();
    return builder;
    
补充说明

直接用new HttpClient(new HttpLoggingHandler())时,是你手动创建Handler实例,不需要DI参与;但切换到HttpFactory模式后,所有加入管道的DelegatingHandler都得由DI容器管理,框架会自动处理Handler之间的嵌套关系,所以必须先完成注册。

内容的提问来源于stack exchange,提问作者Ferccino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:17:07