简体   繁体   English

动作过滤器中的ASP.NET Web API读取模型

[英]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). 当需要从动作过滤器(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). 一旦无法再次读取模型(我认为ReadAsAsync <>在下划线流中移动位置)后,这可以正常工作,但不幸的是在调用ReadAsAsync <>之后。 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? 有什么想法如何在动作过滤器中读取模型或如何解决此问题?

In Web API, the response body is a read forward only stream. 在Web API中,响应主体是只读流。 So once you read it, you cannot read it again. 因此,一旦您阅读它,便无法再次阅读。

Consider passing the something in query params or some other parameter , other than body. 考虑将something传递给查询参数或其他参数 ,而不是body。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM