2

只有当我有某个 DelegatingHandler 拦截调用时,我的应用程序才会弹出一个非常奇怪的错误。它的要点是,当请求通过我的 DelegatingHandler 时,对于 Web 服务器仅接收的第一个请求,HttpContext.Current 为空。因此,如果我是部署代码后第一个使用我的 API 的人,我会收到错误消息。否则,我很酷。

以下是错误发生方式的概述:

  1. 请求进入委托处理程序
  2. 处理程序遍历其整个SendAsync函数并通过调用结束return await base.SendAsync(request, cancellationToken);
  3. WebAPI 依赖解析器(我使用 simpleinjector)尝试解析 APIController 的依赖
  4. 依赖解析失败,因为HttpContext.Current为空(试图HttpContext.Current.Items为我的IUnitOfWork

所以看起来线程亲和力/上下文仅在我的处理程序中被更改?我不明白。调用堆栈始终显示错误(HttpContext 为空)发生在该 final 中await base.SendAsync(request, cancellationToken);。奇怪的。

这是处理程序代码:

public class RecipeIdValidator:DelegatingHandler
{

    private static string[] _Ignore = new string[] {"api/webhook" };
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if(_Ignore.Any(i=>request.RequestUri.AbsoluteUri.IndexOf(i)!=-1))
            return await base.SendAsync(request, cancellationToken);


        var recipeId = request.GetQueryNameValuePairs().Where(i=>i.Key.Equals("recipeid",StringComparison.InvariantCultureIgnoreCase));

        if (!recipeId.Any())
            return request.CreateErrorResponse(System.Net.HttpStatusCode.Forbidden,"Missing recipeId/api key. Please add this to your request in the form of the querystring ?recipeId=value.");


        CheckValidity(recipeId);


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

0 回答 0