c# - Custom authorization filter logs twice -
i created custom authorization filter checks in it. when check fails writing log file. strange thing every fail writes error text twice log. how make sure logs error once?
public class authorizationfilter : filterattribute, iauthorizationfilter { public void onauthorization(authorizationcontext filtercontext) { var key = “wrong key”; if (key != “correct key”) { datetime datetime = filtercontext.httpcontext.timestamp; string path = path.combine(appdomain.currentdomain.basedirectory, @"logs\log.txt"); using (streamwriter sw = file.appendtext(path)) { sw.writeline(datetime + “| error xyz”); } filtercontext.result = new httpunauthorizedresult(); } } }
assuming have filter registered globally...
public class filterconfig { public static void registerglobalfilters(globalfiltercollection filters) { filters.add(new authorizationfilter()); filters.add(new handleerrorattribute()); } } it fire once when original action run. return 401 unauthorized. status caught asp.net , automatically redirect login page. when login page loads, filter runs again (and presumably fails again).
to make stop doing this, there couple of options.
- inherit
authorizeattributeinstead offilterattribute, iauthorizationfilter. overrideauthorizecoremethod , returnfalsewhen login fails. useallowanonymousattributeattribute on login method (and other methods don't want check). - build own logic either check
allowanonymousattributeor custom attribute. here example of checking attribute within filter.
i suggest use first option. reason in addition automatically gaining functionality of allowanonymousattribute there code deal using output caching in conjunction authorization.
Comments
Post a Comment