1

为了避免必须在每个控制器中的每个视图之前传递进入我网站母版页的数据,我创建了一个 ApplicationController,在其构造函数上设置数据......这种方法的问题是我的视图数据之一must pass 是当前登录用户的个人资料图像的 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 现在不必在每次视图调用时设置所有数据。

[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() 方法实际上无法获取图片 URL,因为没有人登录.. 尽管有 Authorize 属性,但仍会调用这些方法....所以现在,即使在登录后,图片 URL 的 ViewData 也已永久设置为“unknown.png”

其中一些代码不是我的。我刚刚发现了这个错误,但不知道如何修复它。

4

3 回答 3

0

授权在您网站的任何地方都有效吗?如果没有,可能是您错过了 web.config 中的部分吗?

于 2010-08-04T17:18:10.013 回答
0
if (User.Identity.IsAuthenticated){
   ViewData["picture"] = _servicioPortalAdministrator.GetPic(); 
}
else{
   ...
}

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

于 2010-09-13T10:10:05.150 回答
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
}
于 2011-05-23T00:45:18.173 回答