MVC 自定义操作属性
在测试期间(至少)我们正在记录每个控制器/操作的一些低级信息。所有控制器都派生自我们的自定义 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我的项目中,我使用以下内容来验证访问控制器:
这是我的功能类
您只需根据您的情况调整此代码,我希望它变得有用
in my project I use the following to verify access controllers:
Here is my Capability Class
You just need to adapt this code for your case, I hope it become useful
我尝试构建一个适合您情况的简单示例一段时间,但后来意识到我无法将实例数据传递给
Attribute
- 所以说如果我设置了Log 标志为
false
,我无法使用它来直接操作基本控制器的属性。查看这篇文章。
这是我正在使用的代码(无法编译 - 无法传递
this
):也许你可以用反射做一些事情,但情况可能是你必须这样做这就是您一直在做的方式,因为似乎不可能将实例数据获取到属性。
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 aLog
flag tofalse
, 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
):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.