【问题标题】:MVC (ASP) Implement different user roles on the same action when inheritedMVC(ASP)在继承时对同一操作实现不同的用户角色
【发布时间】: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


【解决方案1】:

创建授权过滤器并找到如下所示的控制器和操作。然后保持角色。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2018-04-28
    相关资源
    最近更新 更多