.net Web API DelegatingHandler异步HttpContext=null错误
我的应用程序中出现了一个非常奇怪的错误,只有当我有某个DelegatingHandler拦截调用时才会出现这个错误。其要点是,当请求通过我的DelegatingHandler时,HttpContext.Current对于web服务器只接收到的第一个请求是空的。因此,如果我是部署代码后第一个使用API的人,我会得到错误。否则,我很酷 以下是错误发生方式的概述:.net Web API DelegatingHandler异步HttpContext=null错误,.net,asp.net-web-api,async-await,httpcontext,.net,Asp.net Web Api,Async Await,Httpcontext,我的应用程序中出现了一个非常奇怪的错误,只有当我有某个DelegatingHandler拦截调用时才会出现这个错误。其要点是,当请求通过我的DelegatingHandler时,HttpContext.Current对于web服务器只接收到的第一个请求是空的。因此,如果我是部署代码后第一个使用API的人,我会得到错误。否则,我很酷 以下是错误发生方式的概述: 请求进入委托处理程序 处理程序执行其整个SendAsync函数,并通过调用return await base.SendAsync(requ
SendAsync
函数,并通过调用return await base.SendAsync(request,cancellationToken)结束代码>
HttpContext.Current
为空(尝试获取我的IUnitOfWork的HttpContext.Current.Items
)
wait 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);
}
}
公共类RecipeIdValidator:DelegatingHandler
{
私有静态字符串[]_Ignore=新字符串[]{“api/webhook”};
受保护的重写异步任务SendAsync(HttpRequestMessage请求,System.Threading.CancellationToken CancellationToken)
{
if(_Ignore.Any(i=>request.RequestUri.AbsoluteUri.IndexOf(i)!=-1))
返回wait base.sendaync(请求、取消令牌);
var recipeId=request.GetQueryNameValuePairs()。其中(i=>i.Key.Equals(“recipeId”,StringComparison.InvariantCultureIgnoreCase));
如果(!recipeId.Any())
return request.CreateErrorResponse(System.Net.HttpStatusCode.Forbidden,“缺少recipeId/api密钥。请以querystring?recipeId=value的形式将其添加到请求中”);
检查有效性(recipeId);
返回wait base.sendaync(请求、取消令牌);
}
}
你有吗?我想这已经解决了问题!现在进行更多测试…但初始测试看起来很有希望。荒谬。我怎么会不知道这一点?在新项目中默认启用,但升级后不会启用。这很容易被忽略!