ASP.NET Web API reads input stream twice

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

[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 an input parameter I have "[FromBody] RequestClasses.UpdataData data". I have this to show a help page (using Microsoft.AspNet.WebApi.HelpPage).

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

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

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

+3


source to share


1 answer


By design, ASP.NET Web API can only read the input payload stream once. So, if the parameter bind value reads it, you don't have it. So people tell you in the comments to use parameterless methods and read the payload themselves.



However, you want to have options to see them on the help page. There is a solution for this: decrypt the request in the previous steps. You can use message handlers for this. Please see the following: Encrypt Request / Response in MVC4 WebApi

0


source







All Articles