WPalombini
WPalombini

Reputation: 961

How to catch and save json data posted to restful asp.net web api

I have this code:

[Route]
    public HttpResponseMessage PostData[FromBody] DataModel data)
    {
         ... implementation...
    }

This automatically binds / converts the json data to my data model. However, I would like to save / catch the raw json file that was posted and save it for logging purposes. Any suggestions on how I can achieve this?

Upvotes: 0

Views: 3955

Answers (1)

govin
govin

Reputation: 6693

You can just do the below and then use JSON converter to convert the string to JSON later.

[HttpPost]
public HttpResponseMessage PostData([FromBody] string text)
{
   // log text.
    DataModel data = JsonConvert.DeSerialize<DataModel>(text);
}

Or you can also do,

[HttpPost]
public HttpResponseMessage PostData()
{
    string text = Request.Content.ReadAsStringAsync().Result; 
    //log text           
    DataModel data = JsonConvert.DeSerialize<DataModel>(text);
}

Since you mention it is for logging, you might want to consider doing this in a Web API filter or a delegating handler - to make the logic more centralized instead of having the logic in each action method.

public class LogApiRequest : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var text =  actionContext.Request.Content.ReadAsStringAsync().Result;
            MyLogger.Log(LogLevel.INFO, text);

            base.OnActionExecuting(actionContext);
        }
    }

and then register your filter - typically in WebApiConfig.cs or decorate your action method or controller class with the filter.

config.Filters.Add(new LogApiRequest());

Upvotes: 3

Related Questions