使用以$ P $属性pmaturely从方法返回 [英] Using an attribute to prematurely return from a method

查看:119
本文介绍了使用以$ P $属性pmaturely从方法返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使该检查的条件,然后根据该条件的属性,无论是从执行停止装饰方法还是让装饰方法继续上执行?

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?

该属性的总体目标是,在ASP.NET MVC中,检查是否有用户被授权,要么返回一个特定的 JsonResult (在属性中定义),如果他们没有授权或让装饰方法继续执行。最明显的问题,我这个是有可能看到的是,如果控制器动作是一个不同类型的比的ActionResult JsonResult 的存在一个运行时间错误的可能性。

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.

推荐答案

有关您的具体情况,可以使用ASP.NET MVC的过滤器的做你所需要的。让你的属性扩展 AuthorizeAttribute

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

这篇关于使用以$ P $属性pmaturely从方法返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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