Nadeem Jamali
Nadeem Jamali

Reputation: 1423

MVC (ASP) Implement different user roles on the same action when inherited

I have multiple controllers in my project that do simple basic jobs like Get(int id), Get(), Insert(T t) and Edit(T t). To avoid code duplication I created a GenericController and then inherited all other controllers from this GenericController. Everything works very fine. But I run into issues when I want to implement different user roles on the same controller action when inherited. For example take a look of the code below:

public class GenericController<T>: Controller{

    //other actions

    [HttpGet]
    public async Task<IEnumrable<T>> Get(){
        //necessary action goes here
    }
    [HttpPost]
    public async Task<IActionResult> Insert(T t){
        //necessary action with t
    }    
}

[Authorize]
public class ProductController: GenericController<Product>{

    //Get action is authorized to everyone
    //Insert action is authorized to Manager only
}

[Authorize]
public class EmployeeController: GenericController<Employee>{

    //Get action is authorized to everyone
    //Insert action is authorized to Owner only
}

In the above snippet the Insert action, that is inherited from GenericController has different authorizations in both Product and Generic Controller.

I don't want to duplicate the code in the inherited controllers. But correct authorization is needed as well. Does anyone know the appropriate solution? Any help will be much appreciated.

Upvotes: 0

Views: 149

Answers (1)

Alok Saxena
Alok Saxena

Reputation: 9

Create authorize filter and find the controller and action like below. And then maintain the role.

string actionName = this.ControllerContext.RouteData.Values["action"].ToString();   
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();   

Upvotes: 1

Related Questions