Using an attribute to prematurely return from a method

血红的双手。 提交于 2019-12-13 05:26:03

问题


Is it possible to make an attribute that checks a condition and then based on that condition either stop the decorated method from executing or let the decorated method continue on executing?

And now the obvious question. If so, how? If not, then is there a work around worth checking out?

The overall goal of this attribute is to, in ASP.NET MVC, check if a user is authorized and either return a particular JsonResult (defined in the attribute) if they aren't authorized or let the decorated method keep on executing. The obvious problem I see with this being possible is if the controller action is of a different type than ActionResult or JsonResult that there exists the possibility of a runtime error.


回答1:


For your particular situation, you can use an ASP.NET MVC filter to do what you need. Have your attribute extend AuthorizeAttribute.

public class MustHaveFooAccessAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Return true or false after checking authorization
    }
}



回答2:


This is not possible using attributes - attributes are resolved at compile time. They do not get executed during runtime.

Specific behavior that attributes "control" is managed through reflection.



来源:https://stackoverflow.com/questions/5688790/using-an-attribute-to-prematurely-return-from-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!