从ServiceStackController检索IAuthRepository

时间:2016-10-22 19:28:55

标签: servicestack

我已经升级了一个旧的ASP.Net Mvc项目,该项目使用Servicestack从4.0.40到4.5但我已经看到在调用base.HasRole时我已经通过了IAuthRepository,我想知道是否有从ServiceStackController或IAuthSession获取它的方法

考虑以下代码段

   protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    {
        ViewBag.UICulture = this.UICulture ?? "it-IT";
        ViewBag.MiniProfiler = AppSettings.Get<bool>(Resources.MiniProfilerKey, false);

        if (UserSession.IsAuthenticated)
        {

            ViewBag.IsAdmin = this.UserSession?.HasRole(RoleNames.Admin) ?? false;
            if (!String.IsNullOrEmpty(this.UserAuthName))
            {
                ViewBag.UserName = this.UserAuthName;
            }

            var userSession = UserSession as IFMSAuthUserSession;

            if (userSession != null)
            {
                userSession.UserImpersonated = GetImpersonatedUser(Module);

                var menu = userSession.Menu?.Clone();

                if (menu == null)
                {
                    int t = 0;
                }

                ViewData[Resources.ModulesData] = userSession.GetAuthorizedModules().Skip(1); //salta home
                ViewData[Resources.MenuData] = menu;
                ViewData[Resources.BreadCrumbData] = menu?.LightMenu(Regex.Replace(Request.Url.AbsolutePath, "/$", ""));
            }
        }
    }

在抽象类

中定义的内容
  public abstract class BaseController<T> : ModuleController<T>
    where T : class, ServiceStack.Auth.IAuthSession

其中ModuleController是

  public abstract class ModuleController : ModuleController<MyAuthUserSession>
{ }

1 个答案:

答案 0 :(得分:2)

您可以从ServiceStackController获取,例如:

var ssController = filterContext.Controller as ServiceStackController;
var authRepo = ssController?.AuthRepository;

否则,在ServiceStack之外,您可以直接从AppHost.GetAuthRepository()单例获取,但您需要访问IRequest(例如,ServiceStackRequest中的ServiceStackController提供):< / p>

var authProvider = HostContext.AppHost.GetAuthRepository(req);