访问Controller中的AuthorizationAttribute

时间:2016-08-04 16:28:10

标签: asp.net asp.net-mvc asp.net-mvc-4

我有一个用MVC编写的自定义AuthorizeAttribute。我将它应用于控制器以确保安全性。在我写的AuthorizeAttribute类中,我写了几个我从Web服务调用中收集的变量,我希望在控制器内部访问,以防止再次调用Web服务。这可能吗?

2 个答案:

答案 0 :(得分:1)

您最好的方法是使用HttpContext.Current.Items来存储这些变量,因为该数据仅对单个http请求有效。像这样:

public class CustomAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.User.Identity == null) return false;
        if (!httpContext.Request.IsAuthenticated) return false;

        var user = new WSUser(); //get this from your webservice
        if(user == null) return false;

        httpContext.Items.Add("prop", user.Property);

        return user.Authorized;
    }
}

public class HomeController : Controller
{
    [CustomAuthorize]
    public ActionResult Index()
    {
        var property = (string) HttpContext.Items["prop"];
        return View();
    }
}

您还希望将用于存储和检索HttpContext.Current项的逻辑封装到一个单独的类中,以保持代码清洁并遵循Single responsibility principle

答案 1 :(得分:0)

您可以将这些变量保存在静态类中以存储它。但是,一个优雅的解决方案是拥有一个模型绑定器对象,您可以在控制器中调用它作为参数,并读取静态类并返回所需的属性。 也许,如果你正在应用安全性,最好的是每次调用webservices。

Reference for your custom model binder

相关问题