WebApi2.0 DelegatingHandler - 错误 - 索引超出了数组的范围

时间:2015-08-26 11:38:14

标签: c# asp.net-web-api2

我有一个webapi 2.0项目。我在webapiconfig.cs中注册了两个委托处理程序。有时它会抛出错误"索引超出了数组的范围"并且stact trace显示 - handler2处于handler1处的System.Collections.GenericList.Add(T item)处的错误。我也在使用unityconfig,我正在Global.asax的Application_Start注册,我正在Global.asax的Application_Start注册WebApiconfig 我不知道为什么这样的奇怪的行为,因为它在大多数时间都正常工作,但有时它会抛出这个错误。

WebApiconfig.cs中的我的代码如下 -

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        config.EnableCors();

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

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

        // Web API routes
        config.MapHttpAttributeRoutes();

    }

两个处理程序的代码如下 -

public class Handler1 : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {


        string routeTemplate = ((IHttpRouteData[])request.GetConfiguration().Routes.GetRouteData(request).Values["MS_SubRoutes"])
                                .First().Route.RouteTemplate.ToString();



        IPrincipal principal = new GenericPrincipal(new GenericIdentity(new Guid()), new string[] { "myRole" });
        HttpContext.Current.User = principal;

        return base.SendAsync(request, cancellationToken).ContinueWith(
        (task) =>
        {
            HttpResponseMessage response = task.Result;

            return response;
        }
    );
    }
    }
public class Handler2 : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string routeTemplate = ((IHttpRouteData[])request.GetConfiguration().Routes.GetRouteData(request).Values["MS_SubRoutes"])
                                .First().Route.RouteTemplate.ToString();

        HttpConfiguration config = request.GetConfiguration();
        config.Filters.Add(new Filter1());


        return base.SendAsync(request, cancellationToken).ContinueWith(
        (task) =>
        {
            HttpResponseMessage response = task.Result;

            return response;
        }
    );
    }
}

有人可以帮助我做我应该做的事吗?

1 个答案:

答案 0 :(得分:0)

问题是在处理程序中添加过滤器。 config.Filters.Add(new Filter1());

在GlobalConfig中添加了过滤器,一切运行顺畅。