Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a safe way to get body of a HttpContext request

public static class HttpRequestHelper
{
    public static string RequestBody()
    {
        var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
        bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
        var bodyText = bodyStream.ReadToEnd();
        return bodyText;
    }
}

I plan to call this from ActionFilters to log incoming requests. Of course there could be multiple simultaneous requests.

Is this approach ok?

like image 391
tom Avatar asked Sep 04 '13 22:09

tom


1 Answers

Is your question from the perspective of concurrency or ASP.NET Web API in general? Every request has its own context and you are okay with multiple requests going on in parallel. But here are two things for you to look at.

(1) Since you are using HttpContext, you are locking yourself to web hosting (IIS), which in many cases should be okay. But I would like you to be aware of this.

(2) Your code HttpRequestHelper.RequestBody() will work when called from an action filter, as you mentioned. However, if you try to call this from other places, say a message handler, this will not work. When I say this will not work, parameter binding that binds request body to action method parameter will not work. You will need to seek to the beginning once you are done. The reason it works from action filter is that binding would have already happened by the time action filter runs in the pipeline. This is another thing you might need to be aware of.

like image 169
Badri Avatar answered Sep 19 '22 08:09

Badri