2

I try to create a filter to modify the content. For some reason the var result = await actionContext.Request.Content.ReadAsStringAsync(); does not wait and returns me empty values. I'm sure that there is data. Checked directly inside controller and header. Is there maybe a workaround. Can be blocking, too (HttpContent seems just to have async methods).

 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)
    {
    }
 }
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
MR.ABC
  • 4,712
  • 13
  • 44
  • 88

1 Answers1

0
  1. You should not be accessing the body in an action filter, if you have any thing else accessing the body in parameter binding it might be already gone.
  2. Why are you calling actionExecuted inside the action executing overload? The pattern is one gets called before the action is run and one after.
  3. For some reason it also looks like you are trying to implement the filter pipeline itself inside this method.

If you want to bind data from the body your recommended alternative is to use a formatter. Implement a MediaTypeFormatter and read what you need into a string. See one example

My wild bet here is that something else already read the body stream (and technically you are done at the point) and you can try and rewind it first (it will only work if you are in buffered mode).

Community
  • 1
  • 1
Yishai Galatzer
  • 8,791
  • 2
  • 32
  • 41