Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET Web API reading inputstream twice

I am using ASP .NET Web API and I have a Controller that have code similar to this:

[Route("UpdateData")]
[HttpPost]
public HttpResponseMessage UpdateData([FromBody]RequestClasses.UpdataData data)
{
    string json;
    if (HttpContext.Current.Request.InputStream.Length > 0)
    {
        HttpContext.Current.Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
        {
            json = inputStream.ReadToEnd();
        }
    }

    // Dencrypt json

return Request.CreateResponse(HttpStatusCode.OK);
}

As input parameter I have "[FromBody]RequestClasses.UpdataData data". I have this in order to be able to show a Help page (using Microsoft.AspNet.WebApi.HelpPage).

The data object received in this method is encrypted and I need to decrypt it.

My problem is that I cannot call HttpContext.Current.Request.InputStream because the "[FromBody]RequestClasses.UpdataData data" has disposed my InputStream.

Any good ideas to solve this? As I still need the help page to show which parameters to call the method with.

like image 916
torstenaa Avatar asked Oct 20 '22 09:10

torstenaa


1 Answers

By design ASP.NET Web API can only read the payload input stream once. So, if the parameter binder reads it, you don't have it available. That's way people is telling you in the comments to use parameterless methods, and read the payload yourself.

However, you want to have parameters to see them in the help page. There is a solution for that: do the decryption of the request in previous steps. To do that you can use Message handlers. Please, see this: Encrypt Request/Reponse in MVC4 WebApi

like image 174
JotaBe Avatar answered Oct 22 '22 00:10

JotaBe