开发者

Using an attribute to prematurely return from a method

开发者 https://www.devze.com 2023-02-25 19:58 出处:网络
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?

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 retu开发者_JS百科rn 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.


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
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号