无法读取Web API操作过滤器内容

Gut*_*iro 7 c#-4.0 asp.net-mvc-4 asp.net-web-api

相关问题:Web API操作参数间歇性地为空并且http://social.msdn.microsoft.com/Forums/vstudio/en-US/25753b53-95b3-4252-b034-7e086341ad20/web-api-action-parameter-is -intermittently空

嗨!

我正在ASP.Net MVC WebAPI 4中创建一个ActionFilterAttribute,所以我可以在控制器中应用操作方法中的属性,我们需要验证令牌,然后执行它,如下面的代码:

public class TokenValidationAttribute : ActionFilterAttribute
{
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
        //Tried this way
        var result = string.Empty;
        filterContext.Request.Content.ReadAsStringAsync().ContinueWith((r)=> content = r.Result);

        //And this
        var result = filterContext.Request.Content.ReadAsStringAsync().Result;

        //And this
        var bytes = await request.Content.ReadAsByteArrayAsync().Result;
        var str = System.Text.Encoding.UTF8.GetString(bytes);

        //omit the other code that use this string below here for simplicity
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将内容读为字符串.尝试了这个代码中所述的3种方式,并且所有方法都返回空白.我知道在WebApi中我只能读取一次请求的正文内容,所以我正在评论代码中的其他所有内容,并尝试让它运行以查看我是否得到了结果.关键是,客户端甚至Fiddler报告请求的内容长度315.同样大小也在服务器内容标题上,但是,当我们尝试阅读内容时,它是空的.

如果我删除属性并发出相同的请求,控制器被调用好,Json的反序列化发生完美无瑕.如果我放置属性,我得到的只是内容中的空字符串.它始终发生.相关问题表明并非间歇性.

我究竟做错了什么?请记住,我正在使用ActionFilter而不是DelegatingHandler,因为在执行之前,只有选定的操作需要令牌验证.

感谢帮助!对此,我真的非常感激.

问候...

Gutemberg

Kir*_*lla 15

默认情况下,Web主机(IIS)方案的缓冲区策略是始终缓冲传入请求的流.你可以看看System.Web.Http.WebHost.WebHostBufferPolicySelector.现在你已经想到了,Web Api的格式化程序将使用流,而不会尝试回退它.这是有目的的,因为可以更改缓冲区策略以使传入请求的流不缓冲,在这种情况下,倒带将失败.

因此,在您的情况下,因为您知道请求将始终被缓冲,您可以像下面一样获取传入流并回放它.

Stream reqStream = await request.Content.ReadAsStreamAsync();

if(reqStream.CanSeek)
{
     reqStream.Position = 0;
}

//now try to read the content as string
string data = await request.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)