MVC 自定义操作属性

发布于 2024-12-05 23:31:41 字数 464 浏览 1 评论 0原文

在测试期间(至少)我们正在记录每个控制器/操作的一些低级信息。所有控制器都派生自我们的自定义 BaseController,它重写 OnActionExecuting 来执行日志记录。

我们在 BaseController 中有一个属性来确定是否会发生此日志记录,以便控制器可以重写 OnActionExecuting 本身,重置标志,然后调用“base.OnActionExecuting”。该标志通常为 true,但例如,我们希望针对某些 Json 请求将其关闭。

我们更喜欢做的是创建一个自定义控制器/操作过滤器来处理这个问题,如下所示:

[LogPageAccess(false)]
[HttpGet]
Public ActionResult Foobar()

我确信有一种方法可以做到这一点,但我无法弄清楚如何创建自定义属性并让它重置 BaseController 中的标志。

谢谢...

During testing (at least) we're logging some low-level information for each controller/action. All controllers are derived from our custom BaseController which overrides OnActionExecuting to do the logging.

We have a property in the BaseController that determines whether or not this logging will occur, so that a controller can override OnActionExecuting itself, reset the flag, and then call "base.OnActionExecuting". The flag is normally true, but we'd want to turn it off for some Json requests, for example.

What we'd prefer to do is create a custom controller/action filter to handle that, something like this:

[LogPageAccess(false)]
[HttpGet]
Public ActionResult Foobar()

I'm sure there's a way to do it, but I haven't been able to figure out how to create the custom attribute and have it reset the flag in the BaseController.

Thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残花月 2024-12-12 23:31:41

在我的项目中,我使用以下内容来验证访问控制器:

    [Capability(UserCapability.FileManagement)]
    public ActionResult FileList(FileListRequestModel request, bool ajax = false)
    {
        //code
    }

这是我的功能类

/// <summary>
/// Decorator to MVC class and method to evaluate if a certain capability is enabled
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CapabilityAttribute : AuthorizeAttribute
{
    #region Class Attributes

    private object _capability = null;

    #endregion

    #region Public Methods

    /// <summary>
    /// Create a new capability attribute
    /// </summary>
    /// <param name="capability">Context Value passed to the validator</param>
    public CapabilityAttribute(object capability)
    {
        this._capability = capability;
    }

    /// <summary>
    /// Check if attribute is enabled
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!Capability.Enabled(this._capability))
        {
            throw new UnauthorizedAccessException();
        }
        else
        {
            base.OnAuthorization(filterContext);
        }
    }

    #endregion
}

您只需根据您的情况调整此代码,我希望它变得有用

in my project I use the following to verify access controllers:

    [Capability(UserCapability.FileManagement)]
    public ActionResult FileList(FileListRequestModel request, bool ajax = false)
    {
        //code
    }

Here is my Capability Class

/// <summary>
/// Decorator to MVC class and method to evaluate if a certain capability is enabled
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CapabilityAttribute : AuthorizeAttribute
{
    #region Class Attributes

    private object _capability = null;

    #endregion

    #region Public Methods

    /// <summary>
    /// Create a new capability attribute
    /// </summary>
    /// <param name="capability">Context Value passed to the validator</param>
    public CapabilityAttribute(object capability)
    {
        this._capability = capability;
    }

    /// <summary>
    /// Check if attribute is enabled
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!Capability.Enabled(this._capability))
        {
            throw new UnauthorizedAccessException();
        }
        else
        {
            base.OnAuthorization(filterContext);
        }
    }

    #endregion
}

You just need to adapt this code for your case, I hope it become useful

玩套路吗 2024-12-12 23:31:41

我尝试构建一个适合您情况的简单示例一段时间,但后来意识到我无法将实例数据传递给 Attribute - 所以说如果我设置了 Log 标志为 false,我无法使用它来直接操作基本控制器的属性。

查看这篇文章

这是我正在使用的代码(无法编译 - 无法传递 this):

public class BaseController : Controller
{
    public bool LogPageRequests { get; set; }
}

public class LogPageAccess : ActionFilterAttribute
{
    public LogPageAccess(BaseController baseController, bool log = true)
    {
        baseController.LogPageRequests = log;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Do Whatever
        base.OnActionExecuting(filterContext);
    }
}

public class SomeController : BaseController
{
    [LogPageAccess(this, false)]
    public ActionResult Index()
    {
        return View();
    }
}

也许你可以用反射做一些事情,但情况可能是你必须这样做这就是您一直在做的方式,因为似乎不可能将实例数据获取到属性。

I tried to build out a simple example of your situation for a while, but then realized that I couldn't pass instance data to an Attribute-- so say if I set a Log flag to false, I couldn't use that to directly manipulate the base controller's property.

Check out this SO post.

Here was the code I was playing around with (does not compile -- can't pass this):

public class BaseController : Controller
{
    public bool LogPageRequests { get; set; }
}

public class LogPageAccess : ActionFilterAttribute
{
    public LogPageAccess(BaseController baseController, bool log = true)
    {
        baseController.LogPageRequests = log;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Do Whatever
        base.OnActionExecuting(filterContext);
    }
}

public class SomeController : BaseController
{
    [LogPageAccess(this, false)]
    public ActionResult Index()
    {
        return View();
    }
}

Maybe you can do something with reflection, but it might be the case that you'll have to do it the way you've been doing it since it just doesn't seem possible to get instance data to the attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文