Michal
Michal

Reputation: 1406

ASP.NET Web API read model inside action filter

I have a special case when I need to get some data from request body (or model let say) inside action filter (AuthorizationFilterAttribute). I have found this way:

public async override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
    var model = await actionContext.Request.Content.ReadAsAsync<XYZ>();
    var valueINeed = model.Something;
    etc...
}

This works fine but unfortunately after calling ReadAsAsync<> once it is not possible to read model again (I guess that ReadAsAsync<> move position in underlining stream). Because it can't be read again model not make it into controller action:

public async Task<HttpResponseMessage> Put([FromBody]XYZ order)
{
    // order is null here
}

Any thoughts how to read model in action filter or how to work around this problem?

Upvotes: 0

Views: 773

Answers (1)

Mrchief
Mrchief

Reputation: 76198

In Web API, the response body is a read forward only stream. So once you read it, you cannot read it again.

Consider passing the something in query params or some other parameter, other than body.

Upvotes: 1

Related Questions