c# - Exception filter not working in web api -
i have custom exception filter capable handle errors in controller( common error handling mechanism) ,
public class exceptionhandlingattribute : exceptionfilterattribute { public override void onexception(httpactionexecutedcontext actionexecutedcontext) { var error = actionexecutedcontext.exception; if (error bussinessexcetion) { var exceptionbase = (bussinessexcetion)error; var code = (httpstatuscode)exceptionbase.httpexceptioncode; throw new httpresponseexception(new httpresponsemessage(code) { content = new stringcontent(exceptionbase.message), reasonphrase = "exception" , }); } // log error /* error logging */ loggingfactory.getlogger().logerror(string.format("exception:{0} ||stack trace:{1}", error.message, error.stacktrace), error); throw new httpresponseexception(new httpresponsemessage(httpstatuscode.internalservererror) { content = new stringcontent("an error occurred, contact support team."), reasonphrase = "critical exception" }); } }
i registered filter in fillterconfig file
public static void registerglobalfilters(globalfiltercollection filters) { filters.add(new exceptionhandlingattribute()); filters.add(new handleerrorattribute()); }
but getting error
the given filter instance must implement 1 or more of following filter interfaces: iauthorizationfilter, iactionfilter, iresultfilter, iexceptionfilter
i know exceptionfilterattribute implimented iexceptionfilter filter. why getting error
in order work, need implement system.web.http.filters.exceptionfilterattribute.
public class notimplexceptionfilterattribute : exceptionfilterattribute { log4net.ilog log = log4net.logmanager.getlogger(system.reflection.methodbase.getcurrentmethod().declaringtype); public override void onexception(httpactionexecutedcontext context) { requestdata requestdata = new requestdata(context.request); log.error("notimplexceptionfilterattribute", context.exception); context.response = new httpresponsemessage(httpstatuscode.notimplemented); } }
then, in webapiconfig.cs, register filter:
public static void register(httpconfiguration config) { config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{count}", defaults: new { count = routeparameter.optional } ); config.filters.add(new notimplexceptionfilterattribute()); }
Comments
Post a Comment