gpt4 book ai didi

c# - Controller 和操作的 MVC 属性

转载 作者:太空狗 更新时间:2023-10-29 20:58:00 24 4
gpt4 key购买 nike

有没有办法在 Controller 级别而不是在特定操作上添加属性。例如,假设我的 Controller 中有 10 个操作,而其中只有 1 个操作不需要我创建的特定属性。

[MyAttribute]public class MyController : Controller{    public ActionResult Action1() {}    public ActionResult Action2() {}    [Remove_MyAttribute]    public ActionResult Action3() {}}

我可能会将此 Action 移动到另一个 Controller (但我不喜欢那样),或者我可以将 MyAttribute 应用于除 Action3 之外的所有操作,但只是想是否有更简单的方法?

最佳答案

我知道我的回答有点晚了(将近四年),但我遇到了这个问题并想分享我设计的一个解决方案,它让我几乎可以做原始问题想做的事情,在以防将来对其他人有帮助。

该解决方案涉及一个名为 AttributeUsage 的小 gem,它允许我们在 Controller (甚至任何基本 Controller !)上指定一个属性,然后覆盖(忽略/删除)单个操作或子操作- Controller 根据需要。它们将“级联”到只有最细粒度的属性实际触发的地方:即,它们从最不具体(基本 Controller )到更具体(派生 Controller ),再到最具体(操作方法)。

方法如下:

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, Inherited=true, AllowMultiple=false)]
public class MyCustomFilterAttribute : ActionFilterAttribute
{

private MyCustomFilterMode _Mode = MyCustomFilterMode.Respect; // this is the default, so don't always have to specify

public MyCustomFilterAttribute()
{
}
public MyCustomFilterAttribute(MyCustomFilterMode mode)
{
_Mode = mode;
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (_Mode == MyCustomFilterMode.Ignore)
{
return;
}

// Otherwise, respect the attribute and work your magic here!
//
//
//
}

}

public enum MyCustomFilterMode
{
Ignore = 0,
Respect = 1
}

(我听说你喜欢属性,所以我在属性上放了一些属性!这就是让魔法在最顶层发挥作用的真正原因:允许它们继承/级联,但只允许其中之一执行。)

现在是这样使用的:

[MyCustomFilter]
public class MyBaseController : Controller
{
// I am the application's base controller with the filter,
// so any derived controllers will ALSO get the filter (unless they override/Ignore)
}

public class HomeController : MyBaseController
{
// Since I derive from MyBaseController,
// all of my action methods will also get the filter,
// unless they specify otherwise!

public ActionResult FilteredAction1...
public ActionResult FilteredAction2...

[MyCustomFilter(Ignore)]
public ActionResult MyIgnoredAction... // I am ignoring the filter!

}

[MyCustomFilter(Ignore)]
public class SomeSpecialCaseController : MyBaseController
{
// Even though I also derive from MyBaseController, I can choose
// to "opt out" and indicate for everything to be ignored

public ActionResult IgnoredAction1...
public ActionResult IgnoredAction2...

// Whoops! I guess I do need the filter on just one little method here:
[MyCustomFilter]
public ActionResult FilteredAction1...

}

我希望它能编译,我从一些类似的代码中提取它并对其进行了一些搜索和替换,因此它可能并不完美。

关于c# - Controller 和操作的 MVC 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/857142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com