Reputation: 1411
I created a custom authorization filter with some checks in it. When the check fails it is writing to a log file. The strange thing is that with every fail it writes the error text twice to the log. How to make sure it only logs the 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();
}
}
}
Upvotes: 0
Views: 297
Reputation: 56849
Assuming you have the filter registered globally...
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizationFilter());
filters.Add(new HandleErrorAttribute());
}
}
It will fire once when the original action is run. Then it will return 401 unauthorized. This status is caught by ASP.NET and will automatically redirect to the login page. When the login page loads, your filter runs again (and presumably fails again).
To make it stop doing this, there are a couple of options.
AuthorizeAttribute
instead of FilterAttribute, IAuthorizationFilter
. Override the AuthorizeCore
method and return false
when the login fails. Use the AllowAnonymousAttribute
attribute on your login method (and any other methods you don't want to check).AllowAnonymousAttribute
or a custom attribute. Here is an example of checking for an attribute within a filter.I suggest you use the first option. The reason is that in addition to automatically gaining the functionality of the AllowAnonymousAttribute
there is also some code to deal with using output caching in conjunction with authorization.
Upvotes: 1