Web API Action Filter Content Cannot Be Read

Related question: Web API action parameter is interrupted by null and http://social.msdn.microsoft.com/Forums/vstudio/en-US/25753b53-95b3-4252-b034-7e086341ad20/web-api-action-parameter -is-intermittently-null

Hello!

I am creating an ActionFilterAttribute in ASP.Net MVC WebAPI 4, so I can apply the attribute in the action methods on the controller that we need to validate the token before executing it as the following code:

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 } } 

I am trying to read the contents as a string. I tried 3 methods, as indicated in this code, and they all return empty. I know that in WebApi I can only read the contents of the request body once, so I comment on everything else in the code and try to run it to see if I get the result. The fact is that the client and even Fiddler report 315 lengths of the contents of the request. The same size also falls into the header of the server content, but when you try to read the contents, it is empty.

If I remove the attribute and make the same request, the controller will work out well, and Json deserialization will be flawless. If I put an attribute, all I get is an empty string from the content. This happens ALWAYS. Not intermittent, as they say in related matters.

What am I doing wrong? Keep in mind that I'm using ActionFilter instead of DelegatingHandler, because only the selected actions require a token check before execution.

Thanks for the help! I really appreciate that.

Yours faithfully...

Gutemberg

+7
asp.net-web-api asp.net-mvc-4
source share
1 answer

By default, the Web Host Scripting (IIS) buffer policy is that incoming requests are always buffered. You can look at System.Web.Http.WebHost.WebHostBufferPolicySelector . Now, as you understand, Web Api formatter will consume the stream and will not try to rewind it. This is special because you can change the buffer policy so that the incoming request stream is not buffered, in which case the rewind will not end.

So, in your case, since you know that the request will always be buffered, you can get the input stream as shown below and rewind it.

 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(); 
+15
source share

All Articles