C# 如何在派生的控制器操作上添加不同的操作筛选器?
我的控制器使用不同的授权筛选器执行相同的操作C# 如何在派生的控制器操作上添加不同的操作筛选器?,c#,asp.net-mvc,C#,Asp.net Mvc,我的控制器使用不同的授权筛选器执行相同的操作 public class RoomAController:Controller { [Authorize(Roles = "RoomAEditors")] public ActionResult SaveNote() { ... } } public class RoomBController:Controller { [Authorize(Roles = "RoomBEditors")]
public class RoomAController:Controller
{
[Authorize(Roles = "RoomAEditors")]
public ActionResult SaveNote()
{
...
}
}
public class RoomBController:Controller
{
[Authorize(Roles = "RoomBEditors")]
public ActionResult SaveNote()
{
...
}
}
SaveNote
的代码在两个控制器中完全相同。所以我想把它放在一个像这样的基本控制器中
public abastract class BaseController:Controller
{
public ActionResult SaveNote()
{
...
}
}
有了这个基本控制器,如何在各个控制器中添加操作过滤器
public class RoomBController:BaseController
{
[Authorize(Roles = "RoomBEditors")]
// how to add different authorization filters on the SaveNote action?
}
在我的抽象基本控制器上,有一个
SaveNote
操作。您将在每个SaveNote()操作中的BaseController(base)上调用SaveNote()。您可以在BaseController中实现SaveNote方法,并使用适当的授权筛选器角色在RoomA和RoomB控制器中重写它
public abstract class BaseController : Controller
{
virtual public ActionResult SaveNote()
{
throw new NotImplementedException();
}
}
public class RoomAController : BaseController
{
[Authorize(Roles = "RoomAEditors")]
public override ActionResult SaveNote()
{
return base.SaveNote();
}
}
public class RoomBController : BaseController
{
[Authorize(Roles = "RoomBEditors")]
public override ActionResult SaveNote()
{
return base.SaveNote();
}
}
我认为@Skyler的答案是正确的,尽管我建议你重新考虑你的设计。对我来说,这更像是一种代码味道……我可以想到两个选项:选项1:覆盖方法选项2:使用源自
AuthorizeAttribute
的自定义授权属性,并具有一些逻辑,可以引用变量或方法来确定要使用哪个角色