leosbrf
leosbrf

Reputation: 159

How to read the body message from a http request using ASP .NET 5

My scenario:

I'm using ASP .NET 5 Web API and I'm using content-type: application/json to post data to server.

Message:

Request headers
{...}
Content-Type:application/json
{...}

Request payload
{"Property1":"2280910","Property2":"734"}

MyController method:

[HttpPost]
public MyClassOutput GetDataRequest([FromBody] GetDataInput input) { ... }

I override the OnException method from the ExceptionFilterAttribute class which gives me the ExceptionContext instance. I want to get the parameter values from the request for exceptions logging purposes. I tried to read the body content, but it is empty.

public override void OnException(ExceptionContext context)
{
   JsonSerializer serializer = new JsonSerializer();
   var content = context.HttpContext.Request;

   using (var stream = new StreamReader(content.Body, Encoding.UTF8))
   using(var jsonTextReader = new JsonTextReader(stream))
   {
       var bodyContent = serializer.Deserialize(jsonTextReader);
       if (bodyContent != null)
           exceptionData.Parameters = bodyContent.ToString();
   }
}

Can anyone give me directions?

Upvotes: 1

Views: 2792

Answers (2)

leosbrf
leosbrf

Reputation: 159

Since you can't read the content stream twice because of how ASP .NET implements the model binding process, the solution that I found to get the parameters values was in the context.ModelState.Values property. As simple as this... (I did not realize this before).

Upvotes: 0

tdragon
tdragon

Reputation: 3329

I assume you created your own attribute for exception handling, implementing ExceptionFilterAttribute and overrided OnException(HttpActionExecutedContext actionExecutedContext) method. Basically, you have to revert the position in content stream to 0, as it was already read by the framework when calling proper controller method. Your code should look something like this:

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnException(actionExecutedContext);

        var content = actionExecutedContext.Request.Content;
        using (var streamReader = new StreamReader(content.ReadAsStreamAsync().Result))
        {
            streamReader.BaseStream.Position = 0;
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                var serializer = JsonSerializer.Create();
                var parameters = serializer.Deserialize<GetDataInput>(jsonReader);
            }
        }
    }

Upvotes: 3

Related Questions