'DelegatingHandler' 列表无效,因为 'handler' 的 属性 'InnerHandler' 不为空

The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'handler' is not null

我有一个全局添加的自定义消息处理程序,如下所示:

public class CustomerHandler : DelegatingHandler
{
    public CustomHandler(HttpConfiguration httpConfiguration)
    {
        InnerHandler = new HttpControllerDispatcher(httpConfiguration); 
    }
}

config.MessageHandlers.Add(new CustomHandler(config));

但是,我收到以下错误:

The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'CustomHandler' is not null. Parametername: handlers

所以我把代码改成了:

config.MessageHandlers.Add(new CustomHandler(config) { InnerHandler = null });

我得到一个错误:

ArgumentNullException

当我将处理程序添加到单个路由时,它工作正常。

var customHandler = new CustomHandler(config);

config.Routes.MapHttpRoute(
  name: "default",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional },
  constraints: new { id = @"^[0-9]+$" },
  handler: customHandler
);

所以当Innerhandler设置正确或为空时它总是抛出异常。

我错过了什么?

编辑

此自定义处理程序用于检查特定 header 是否在请求中,如果找到,则从内存缓存中获取用户详细信息。从处理程序更改为模块是否更有意义?

首先,您应该阅读 HTTP Message Handlers in ASP.NET Web API 以更好地了解处理程序。

Message handlers are called in the same order that they appear in MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.

Notice that you don't need to set the inner handlers; the Web API framework automatically connects the message handlers.

如果打算将处理程序添加到管道中,则不应设置内部处理程序。框架将根据委托处理程序添加到管道的顺序来执行此操作。

直接将处理程序添加到路由时,不需要内部处理程序,这就是它按照您在 OP 中所述工作的原因。

通常当您在批处理或循环中重复使用相同的 "Handler" 实例时会发生此错误。

在每个请求结束时正确处理 HttpClient 可确保您始终重新开始:

        using (var client = new HttpClient(
                HttpClientFactory.CreatePipeline(
                new HttpClientHandler
                {
                    CookieContainer = new CookieContainer(),
                    UseCookies = true
                },
                new DelegatingHandler[] { new CustomHandler() })))
        {

            var content = new StringContent(request, Encoding.UTF8,"text/xml");

            using (var response = await client.PostAsync(requestUrl, content))
            {
                // DO response processing
            }
        }

希望对您有所帮助。

在我的例子中,我收到该错误消息是因为我的下面的 RegisterGlobalFilters 方法被多次调用,这是由配置错误引起的,因此处理程序被添加到 MessageHandlers 两次。只需确保只添加一次即可。

using System.Web.Http;
...
public static void RegisterGlobalFilters(HttpConfiguration httpConfiguration)
{
    httpConfiguration.MessageHandlers.Add(new MyDelegatingHandler());
}