Last post Mar 17, 2016 06:13 PM by deepalgorithm
Mar 15, 2016 10:29 PM|rover83|LINK
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;
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.");
//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.");
Models.Utils.CreateClientErrorResponse(actionContext.Request, 453, "User does not have Smartphone Photographer role");
Models.Utils.CreateClientErrorResponse(actionContext.Request, 454, "User is not confirmed");
var UserID = int.Parse(ticket.Properties.Dictionary["UserID"]);
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
Mar 17, 2016 06:13 PM|deepalgorithm|LINK
I've had similar requirements in the past. Generally, you should avoid doing dependency injection into Attributes.
I can't explain it better then this stack overflow answer.