locked
Attributes and DI RRS feed

  • Question

  • User3112162 posted

    Hello

    Standard practice to use attributes in ASP.NET MVC (i.e. Authorization filters etc). I have extended AuthorizationAttribute the following way:

        public class AuthorizeApiFilter : AuthorizeAttribute
        {
            public override void OnAuthorization(HttpActionContext actionContext)
            {
                string token = string.Empty;
                AuthenticationTicket ticket;
    
                token = (actionContext.Request.Headers.Any(x => x.Key == "Authorization")) ? actionContext.Request.Headers.Where(x => x.Key == "Authorization").FirstOrDefault().Value.SingleOrDefault().Replace("Bearer ", "") : "";
    
                if (token == string.Empty)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Missing 'Authorization' header. Access denied.");
                    return;
                }
    
                //your OAuth startup class may be called something else...
                ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);
    
                if (ticket == null)
                {
                    Models.Utils.CreateClientErrorResponse(actionContext.Request, 490, "Invalid token decrypted.");
                    return;
                }
    
                if (!bool.Parse(ticket.Properties.Dictionary["IsSmartphonePhotographerRole"]))
                {
                    Models.Utils.CreateClientErrorResponse(actionContext.Request, 453, "User does not have Smartphone Photographer role");
                    return;
                }
    
                if (!bool.Parse(ticket.Properties.Dictionary["IsEmailConfirmed"]))
                {
                    Models.Utils.CreateClientErrorResponse(actionContext.Request, 454, "User is not confirmed");
                    return;
                }
    
                var UserID = int.Parse(ticket.Properties.Dictionary["UserID"]);
                actionContext.Request.Properties.Add("UserID", UserID);
                base.OnAuthorization(actionContext);
            }
        }

    It works and works fine. But I want to write logs when something going wrong (i.e. exception suddenly appeared). But I pass log object as abstraction (interface) to controller. It's necessary for Dependency Injection. How Attributes work with DI and work at all?

    Tuesday, March 15, 2016 10:29 PM

All replies