我正在Visual Studio中构建一个 MVC 5 Web应用程序。我在项目中添加了区域,其中包含特定于管理员角色的用户的功能。
但是,管理员和默认用户都需要类似的功能和视图。例如,拿这个
MyProject --> Controllers --> MyController --> MyActionResult
MyProject --> Areas --> Admin --> Controllers --> MyController --> MyActionResult
两个Controller文件夹都包含一个ActionResult,它包含相同的逻辑并返回相同的View。视图将返回部分视图,可以重复使用,因此有助于 DRY (不要重复自己)原则,但是,我想知道以下
如果两个ActionResult方法具有相同的逻辑并返回相同的逻辑 查看,那么两种方法是否需要?违反DRY原则等?
如果管理员需要访问此特定方法,那么它们会被引导到
MyProject - >控制器 - > MyController - > MyActionResult
并设置此方法以允许访问管理员
[Authorize(Roles="Administrator")]
public ActionResult MyActionResult(int id)
{
}
任何有关此方面的帮助或建议都会非常有用,我们总是尽量遵循开发团队的最佳实践。
谢谢大家。
答案 0 :(得分:1)
我喜欢我的区域是特定于域或子域的 - 不是用户或特定于安全性的。正如您已经提到的那样,使用Authorize annotations注释您的方法/类。
If both ActionResult methods have the same logic and return the same View, then is there a need for both methods? Violation of DRY principle etc?
我会说不,你不需要两者,这是对DRY的违反
Would it be better if when the Administrator needed to access this particular method, they were directed to
> MyProject --> Controllers --> MyController --> MyActionResult
当然,我认为这是更好的,也是最佳实践
Or is this some kind of violation, i.e., the users in Administrator role should only be viewing pages within the Area that was setup for functionality specific to them?
没办法。我们始终具有域和子域的粒度安全性。使用您的授权注释来控制访问。
答案 1 :(得分:0)
如果我已正确理解该问题,我会考虑包含共享功能的基本控制器,并且可以将其他代码添加到管理区域控制器中。
关于视图,如果用户是管理员,我只会使用一些c#/ vb代码来显示某些代码
如:
@if (Roles.IsUserInRole( "Administrator" ) )
答案 2 :(得分:0)
使用未实际路由到的公共区域,但包含多个区域共有的功能。您可以在那里保留共享视图并通过继承共享控制器方法。