在MasterPage中帮助asp.net mvc和ViewData

时间:2010-08-04 17:10:31

标签: asp.net asp.net-mvc master-pages viewdata

为了避免在每个控制器中的每个视图之前传递进入我网站母版页的数据,我创建了一个ApplicationController,在其构造函数上设置数据......这种方法的问题之一是我必须传递的viewdatas是当前登录用户的配置文件Image的URL。

[Authorize(Roles = "Administrator")]
    public abstract class AdministratorController : Controller
    {
        private IPortalAdministratorServices _servicioPortalAdministrator;
        public AdministratorController()
        {
            _servicioPortalAdministrator = new PortalAdministratorServices();
            ViewData["associates"] = _servicioPortalAdministrator.getAssociates();
            ViewData["picture"] = _servicioPortalAdministrator.GetPic();        

        public AdministratorController(IPortalAdministratorServices service)
        {
            _servicioPortalAdministrator = service;
            }

    }

所以我的公司控制器继承自AdministratorController,现在不必在每次View Call上设置所有数据。

[Authorize(Roles = "Administrator")]
public class CompaniesController : AdministratorController
{
    private ICompaniasServices _service;

    public CompaniesController()
    {
        _service = new CompaniasServices(new ModelStateWrapper(this.ModelState));

    }

    public CompaniesController(ICompaniasServices service)
    {
        _service = service;
    }

问题在于:

当我尝试手动访问公司控制器而没有实际登录方法时,GetPic()实际上无法获取图片网址导致没有人登录..并且尽管授权,这些方法仍然被调用属性....所以现在,即使在登录ViewData之后,图片网址仍被永久设置为“unknown.png”

有些代码不是我的......我刚刚发现了这个bug,但无法弄清楚如何修复它。

3 个答案:

答案 0 :(得分:0)

授权是否适用于您网站的任何位置?如果没有,您是否错过了web.config中的部分?

答案 1 :(得分:0)

if (User.Identity.IsAuthenticated){
   ViewData["picture"] = _servicioPortalAdministrator.GetPic(); 
}
else{
   ...
}

这是你可以使用的东西吗?

答案 2 :(得分:0)

从构造函数中删除实现,添加此过滤器,然后您的用法如下所示:[Authorize(Roles =“Administrator”),AdministratorServices]。

public class AdministratorServicesAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var filter = new AdministratorServicesFilter(new PortalAdministratorServices());
            filter.OnActionExecuting(filterContext);
        }
    }

public class AdministratorServicesFilter : IActionFilter
{
    private readonly IPortalAdministratorServices  _servicioPortalAdministrator;

    public AdministratorServicesFilter(IPortalAdministratorServices servicioPortalAdministrator)
    {
        _servicioPortalAdministrator = servicioPortalAdministrator;
    }

    #region IActionFilter Members

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewData["associates"] = _servicioPortalAdministrator.getAssociates();
        filterContext.Controller.ViewData["picture"] = _servicioPortalAdministrator.GetPic();
    }

    #endregion
}