我尝试创建一个过滤器来修改内容。由于某种原因
var result = await actionContext.Request.Content.ReadAsStringAsync();
不等待并返回空值。我确定有数据。直接在 Controller 和 header 内部检查。是否有解决方法。也可以阻塞(HttpContent 似乎只有异步方法)。
public class AsyncAttribute : FilterAttribute, IActionFilter
{
public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
await InternalActionExecuting(actionContext, cancellationToken);
if (actionContext.Response != null)
{
return actionContext.Response;
}
HttpActionExecutedContext executedContext;
try
{
var response = await continuation();
executedContext = new HttpActionExecutedContext(actionContext, null)
{
Response = response
};
}
catch (Exception exception)
{
executedContext = new HttpActionExecutedContext(actionContext, exception);
}
await InternalActionExecuted(executedContext, cancellationToken);
return executedContext.Response;
}
public virtual async Task InternalActionExecuting(HttpActionContext actionContext, CancellationToken cancellationToken)
{
//////////////////////////////////////////////////////////////////////////
var result = await actionContext.Request.Content.ReadAsStringAsync();// <------------------------------------------------------
//////////////////////////////////////////////////////////////////////////
}
public virtual async Task InternalActionExecuted(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
}
}
最佳答案
- 您不应该在操作过滤器中访问正文,如果您有任何其他访问参数绑定(bind)中正文的内容,它可能已经不存在了。
- 为什么要在 Action 执行重载中调用 actionExecuted?模式是在操作运行之前调用一个,在操作运行之后调用一个。
- 出于某种原因,您似乎也在尝试在此方法中实现过滤器管道本身。
如果你想绑定(bind)正文中的数据,你推荐的替代方法是使用格式化程序。实现 MediaTypeFormatter 并将您需要的内容读入字符串。 See one example
我敢打赌,其他东西已经读取了正文流(从技术上讲,你已经完成了这一点),你可以先尝试倒带它(只有在缓冲模式下它才会起作用)。
关于c# - WebAPI ActionFilter 等待 ExecuteActionFilterAsync 无结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23623276/