【发布时间】:2017-01-17 19:53:25
【问题描述】:
我的项目中有多个控制器,它们执行简单的基本工作,例如 Get(int id)、Get()、Insert(T t) 和 Edit(T t)。为了避免代码重复,我创建了一个 GenericController,然后从这个 GenericController 继承了所有其他控制器。一切都很好。但是当我想在继承时在同一个控制器操作上实现不同的用户角色时,我遇到了问题。例如看看下面的代码:
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
}
在上面的 sn-p 中,继承自 GenericController 的 Insert 操作在 Product 和 Generic Controller 中具有不同的授权。
我不想在继承的控制器中复制代码。但也需要正确的授权。有谁知道合适的解决方案?任何帮助将不胜感激。
【问题讨论】:
-
也许不是最好的方法,但也许它适合:为什么你不只检查 Insert 方法中的用户角色,如果不是 Manager 返回 Unauthorized。
标签: c# asp.net-mvc authorization code-duplication