asp.net MVC5 - Dependency Injection and AuthorizeAttribute

后端 未结 3 1805
旧时难觅i
旧时难觅i 2021-02-13 00:59

I searched a long time for a solution for my problem. I have a custom AuthorizeAttribute that needs a Dependency to a \"Service\" that has access to a DbContext. Sadly the Depe

3条回答
  •  被撕碎了的回忆
    2021-02-13 01:21

    In ASP.NET Core you can request services easily as below:

    public class CustomAuthAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            // var user = context.HttpContext.User;
    
            // if (!user.Identity.IsAuthenticated)
            // {
            //     context.Result = new UnauthorizedResult();
            //     return;
            // }
    
            var userService = context.HttpContext.RequestServices.GetService(typeof(UserService)) as UserService;
        }
    }
    

提交回复
热议问题