Sunday, 15 June 2014

c# - .NET Web API - Add Logging -



c# - .NET Web API - Add Logging -

i'm looking help on best way handle api logging. i'd log requests , responses either sql or textfile if that's best way. i've been inserting row logs table in sql server. static method called logaction, , run near end of every controller in web api. log exceptions caught well. there way mvc web api natively, or on right track?

currently looks this:

// log api phone call system.xml.serialization.xmlserializer x = new system.xml.serialization.xmlserializer(request.gettype()); stringwriter s = new stringwriter(); x.serialize(s, request); utilities.logaction(utilities.logtype.main, false, response.tostring(), s.tostring(), "maincontroller: successful");

is there way log api actions natively? feels wrong me because if happened between static method , returning response, log no longer valid. effective way log api actions?

for logging calls api actions, have used custom attribute this:

public class logapirequestattribute : system.web.http.filters.actionfilterattribute { /// <summary> /// web api controllers /// </summary> /// <param name="actionexecutedcontext"></param> public override void onactionexecuted(httpactionexecutedcontext actionexecutedcontext) { base.onactionexecuted(actionexecutedcontext); var request = actionexecutedcontext.request; var response = actionexecutedcontext.response; var actioncontext = actionexecutedcontext.actioncontext; // log api phone call ... } }

you may need check around actionexecutedcontext see if has request , response info want. may want override onactionexecuting method instead or also.

then decorate web api controller attribute:

[logapirequest] public void post(somethinginputmodel thing) { // controller code ... }

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

No comments:

Post a Comment