将ASP.NET MVC属性和动作过滤器注释组合在一起 [英] Combine ASP.NET MVC attributes and action filters annotations together

查看:69
本文介绍了将ASP.NET MVC属性和动作过滤器注释组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的某些控制器操作要求对用户进行身份验证.这些操作用自定义的 [Authorize] 属性标记.幕后,自定义成员资格提供者做了一些魔术,其中包括将一些临时数据设置到公共线程中.

some of my controller actions require a user to be authenticated. Those actions are flagged with a custom [Authorize] attribute. Behind the scene, a custom membership provider does some magic, among which setting some temporary data into the common-thread.

在每个需要身份验证的操作结束时,都需要调用 OnActionExecuted()过滤器以清理线程.这是通过另一个名为 [CleanupContext] 的自定义属性完成的.

At the end of each action that required an authentication, a call to the OnActionExecuted() filter is required to cleanup the thread. This is done via another custom attribute called [CleanupContext].

所以我的动作如下:

[Authorize]
[CleanupContext]
public ViewResult Action()
{
   ...
}

由于这两个总是一起使用,因为我很懒,并且因为我担心有一天某个开发人员可能忘记放置一个或另一个,所以我们最终会出现一些怪异的行为:是否有一种方法可以将它们组合在一起归为一个属性?

Since those two are always used together, since I am lazy and since I fear that someday one dev might forget to put one or the other and we end up with some weird behavior: is there a way to combine them into one attribute?

[AuthorizeAndCleanup]
public ViewResult Action()
{
   // Aaah, if only it could look like this :D
}

非常感谢!

推荐答案

您可以从

You could derive from AuthorizeAttribute in order to do your custom authorization stuff and implement IActionFilter in order to have access to the OnActionExecuting and OnActionExecuted events (to do your custom cleanup code):

public class AuthorizeAndCleanupAttribute : AuthorizeAttribute, IActionFilter
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // TODO: your custom authorization logic
        return base.AuthorizeCore(httpContext);
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // TODO: your custom cleanup code
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
    }
}

很显然,您应该意识到,如果授权失败,则将永远不会执行 OnActionExecuting 事件或 OnActionExecuted 事件(也称为 AuthorizeCore 方法返回false),因此如果要返回false,请确保使用此方法进行清理.

Obviously you should be aware that neither the OnActionExecuting or the OnActionExecuted events will ever be executed if the authorization fails (a.k.a. the AuthorizeCore method returns false) so make sure you do your cleanup in this method if you are about to return false.

这篇关于将ASP.NET MVC属性和动作过滤器注释组合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆