ben cevabım oyuna biraz geç (neredeyse dört yıl) olduğunu biliyorum, ama bu soruya rastladım Gelecekte başkalarına yardımcı olması durumunda, asıl sorunun ne yapmak istediğini hemen hemen yapmamı sağlayan bir çözüm önermek istedim. Çözüm, AttributeUsage
adı verilen küçük bir gem içerir; bu, denetleyicideki (ve hatta tüm temel denetleyicilerinde!) Bir öznitelik belirtmemizi ve gerektiğinde bireysel eylemler veya alt denetleyicileri geçersiz kılmamızı (yok saymayı/kaldırmayı) sağlar. Sadece en granüler özniteliğin gerçekte ateşlendiği yere "kademeli" olacaklardır, yani en spesifik (temel denetleyiciler), daha spesifik (türetilmiş denetleyiciler), en özel (eylem yöntemleri).
[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
}
(ı nitelikler gibi duydum, bu yüzden özellik hakkında bazı özelliklerini koymak Çok üst burada sihirli çalışmasını sağlayan şeylerin gerçekten:
İşte nasıl! Onları/basamaklarını miras izin vermek, ancak bunlardan sadece birini sağlayan yürütmek için)
İşte
var şimdi nasıl kullanıldığını.
[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...
}
Bu derler umut, biraz s bazı benzer koddan çekti ve yaptım Üzerinde arama yapın ve değiştirin, bu yüzden mükemmel olmayabilir.
Teşekkürler David! Tam olarak aklımda olan şey! –