1

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?

2 Answers 2

3

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);
            }
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, @tdragon. After searching around I realized that I can't read the content stream twice if I'm using the asp .net model binding process. The incoming request to the asp.net web api is read as a forward-only stream and that is the reason the content is empty. I better use another approach.
0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.