'DelegatingHandler'列表无效,因为'handler'的属性'InnerHandler'不为null [英] The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'handler' is not null

查看:264
本文介绍了'DelegatingHandler'列表无效,因为'handler'的属性'InnerHandler'不为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义消息处理程序,它按如下方式全局添加:

I have a custom message handler that I add globally as follows:

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

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

但是,出现以下错误:

'DelegatingHandler'列表无效,因为'CustomHandler'的属性'InnerHandler'不为null. 参数名称:处理程序

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

ArgumentNullException

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

When I add the handler to the individual routing, it works fine.

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或将其设置为null时,它总是会引发异常.

So it always throws an exception when the Innerhandler is set correctly or null.

我想念什么?

编辑

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

This custom handler is used to check that a particular header is in the request and if found, gets the user details from a memory cache. Would it make more sense to change from a handler to a module?

推荐答案

首先,您应该阅读 ASP.NET Web API中的HTTP消息处理程序,以更好地了解这些处理程序.

First you should read up on HTTP Message Handlers in ASP.NET Web API to get a better understanding of the handlers.

消息处理程序的调用顺序与它们出现的顺序相同 MessageHandlers 集合.因为它们是嵌套的,所以响应 消息在另一个方向传播.也就是说,最后一个处理程序是 第一个获得响应消息的人.

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.

请注意,您不需要设置内部处理程序; Web API 框架会自动连接消息处理程序.

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

如果打算将处理程序添加到管道中,则不应设置内部处理程序.该框架将根据委派处理程序添加到管道的顺序进行操作.

If intending to add the handler to the pipeline then you should not set the inner handler. the framework will do that based on the order the delegating handler was added to the pipeline.

将处理程序直接添加到路由时,不需要内部处理程序,因此这就是您在OP中所述的原因.

When adding the handler to the route directly there is no need for the inner handler so that is why it works as you stated in the OP.

这篇关于'DelegatingHandler'列表无效,因为'handler'的属性'InnerHandler'不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆