Wednesday, 15 May 2013

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



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

i have code:

[route] public httpresponsemessage postdata[frombody] datamodel data) { ... implementation... }

this automatically binds / converts json info data model. however, save / grab raw json file posted , save logging purposes. suggestions on how can accomplish this?

you can below , utilize json converter convert string json later.

[httppost] public httpresponsemessage postdata([frombody] string text) { // log text. datamodel info = jsonconvert.deserialize<datamodel>(text); }

or can do,

[httppost] public httpresponsemessage postdata() { string text = request.content.readasstringasync().result; //log text datamodel info = jsonconvert.deserialize<datamodel>(text); }

since mention logging, might want consider doing in web api filter or delegating handler - create logic more centralized instead of having 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 register filter - typically in webapiconfig.cs or decorate action method or controller class filter.

config.filters.add(new logapirequest());

c# asp.net json asp.net-web-api

No comments:

Post a Comment