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.

  1. inherit authorizeattribute instead of filterattribute, iauthorizationfilter. override authorizecore method , return false when login fails. use allowanonymousattribute attribute on login method (and other methods don't want check).
  2. build own logic either check allowanonymousattribute or 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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -