C#DelegatingHandler错误

时间:2014-03-18 14:36:03

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

我有以下简单的委托处理程序,它从请求中读取标头,检查令牌是否在内存缓存中,如果没有,则创建一个新的响应消息。

public class SessionHandler : DelegatingHandler
{
    private LogService logService = new LogService();

    public static string AuthToken = "X-Auth-Token";

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;

        try
        {
            var headers = request.Headers;
            if (headers.Contains(AuthToken))
            {
                string auth = headers.GetValues(AuthToken).First();
                request.Properties[AuthToken] = auth;

                Session session = Cache.GetSession(auth);

                //Session doesn't exist
                if (session == null)
                    response = new HttpResponseMessage(HttpStatusCode.Conflict);
            }

            else
                response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
        catch (Exception ex)
        {
            //
        }

        //Handle the response message
        if (response != null)
        {
            var task = new TaskCompletionSource<HttpResponseMessage>();
            task.SetResult(response);
            return await task.Task;
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

我记录了每一行,一切正常。但是我的控制器返回500错误。而且在到达控制器之前,我不知道错误是在处理程序的最后一次返回还是在管道中的其他地方。

控制器继承自此基本控制器:

public abstract class BaseController : ApiController
{
    protected Session session;

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        try
        {
            logService.Logger().Info("BaseController.Initialize");

            string authToken = controllerContext.Request.Properties[SessionHandler.AuthToken] as string;
            session = Cache.GetSession(authToken);

        }
        catch (Exception ex)
        {
            //
        }

        base.Initialize(controllerContext);
    }

}

永远不会到达日志信息(&#34; BaseController.Initialize&#34;),因此错误发生在其他地方。

进一步调试后,当我按如下方式评论ma路线时:

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

在委派处理程序中执行以下行:

return await base.SendAsync(request, cancellationToken);

抛出以下异常:

System.InvalidOperationException: The inner handler has not been assigned.

为什么呢?我该如何解决这个问题?

0 个答案:

没有答案