1
\$\begingroup\$

1. Backstory

I recently starting programming and I found out that Entity Framework works perfect for my small-sized applications due its simplicity.

I've made my custom authorize attribute for MVC controllers and controller methods to check if the current user has a certain role (which is an enum type in my case).

The following code represents my authorize attribute:

public class HasRoleAttribute : ActionFilterAttribute
{
    private Role _role;

    public HasRoleAttribute(Role role)
    {
        this._role = role;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var context = new FactoryManagementContext();

        var userName = filterContext.HttpContext.User.Identity.Name;
        var user = context.Users.FirstOrDefault(item => item.UserName == userName);      

        var hasRole = user.Role == _role;

        if (user == null || !hasRole)
        {
            // If this user does not have the
            // required permission then redirect to login page
            var url = new UrlHelper(filterContext.RequestContext);
            var loginUrl = url.Content("/Account/Login");
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
        }
    }
}

public enum Role 
{
    Engineer,
    Manager,
    Admin
}

2. Question

It works as a charm, but I have only one question: is it necessary to initialize the database context every single time when authorizing a user?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You should not instanciate a new DbContext each time your code go throw your ActionFilter.
What you should do is to use dependency injection and to define an execution scope.

Because you are using .net Framework and not .net core, I advise you to look into DI providers such as Autofac or Ninject.

I advise you to look into why to use DI and think about what execution scope you need (probably perScope() in your case).

Hope it helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.