【问题标题】:WebAPI ActionFilter Await ExecuteActionFilterAsync No ResultWebAPI ActionFilter 等待 ExecuteActionFilterAsync 无结果
【发布时间】:2014-06-30 15:45:15
【问题描述】:

我尝试创建一个过滤器来修改内容。由于某种原因 var result = await actionContext.Request.Content.ReadAsStringAsync(); 不等待并返回空值。我确定有数据。直接在控制器和标题内部检查。是否有解决方法。也可以阻塞(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)
    {
    }
 }

【问题讨论】:

  • 你想在这门课上达到什么目的?
  • 我喜欢为一些内容操作的东西设置一个过滤器属性。
  • “我有一个东西可以改变”。谢谢。你能帮我解释一下吗?
  • @MR.ABC 我相信一个示例 HTTP 请求会很好,因为我相信您的问题与此有关。
  • @Matías Fidemraizer 我得走了。我稍后会这样做。使用 json content-type 也许有人会尝试过。

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


【解决方案1】:
  1. 您不应该在操作过滤器中访问正文,如果您在参数绑定中访问正文的任何​​其他内容可能已经不存在了。
  2. 为什么要在执行重载的操作中调用 actionExecuted?模式是在操作运行之前调用一个,之后调用一个。
  3. 由于某种原因,您似乎也在尝试在此方法中实现过滤器管道本身。

如果您想绑定正文中的数据,您推荐的替代方法是使用格式化程序。实现 MediaTypeFormatter 并将您需要的内容读入字符串。 See one example

我敢打赌,其他东西已经读取了正文流(从技术上讲,您已经完成了),您可以先尝试倒带(只有在缓冲模式下才有效)。

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多