asp.net MVC5 - Dependency Injection and AuthorizeAttribute

后端 未结 3 2030
情话喂你
情话喂你 2021-02-13 00:42

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:37

    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;
        }
    }
    

提交回复
热议问题