ServiceStack Session always null in MVC Controller

可紊 提交于 2020-01-03 16:01:23

问题


I'm creating an ASP.NET MVC 4 app using the service stack MVC powerpack, utilizing service stack's auth and session providers. I'm copying lot of logic from the social bootstrap API project. My controllers inherit from the following base controller:

public class ControllerBase : ServiceStackController<CustomUserSession>

which is implemented as:

public class ControllerBase : ServiceStackController<CustomUserSession> {}

CustomUserSession inherits from AuthUserSession:

public class CustomUserSession : AuthUserSession

After I log in, my CustomUserSession OnAuthenticated() method runs, but when I redirect back to my controller, the UserSession is not populated, e.g.

public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
    base.OnAuthenticated(authService, session, tokens, authInfo);
    CustomFoo = "SOMETHING CUSTOM";

    // More stuff
}

public class MyController : ControllerBase
{
    public ActionResult Index()
    {
        // After having authenticated
        var isAuth = base.UserSession.IsAuthenticated; // This is always false
        var myCustomFoo = base.UserSession.CustomFoo; // This is always null

    }
}

Can anyone see what I'm missing here?


回答1:


Refer to issue within ServiceStack Google Group - https://groups.google.com/forum/?fromgroups=#!topic/servicestack/5JGjCudURFU

When authenticating with a JsonSeviceClient (or any serviceClient) from within MVC the cookies are not shared with MVC request/response.

When authenticating within a MVC Controller to ServiceStack, the MVC HttpContext should be sent to ServiceStack. Something like below should work...

var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var response = authService.Authenticate(new Auth
{
  UserName = model.UserName,
  Password = model.Password,
  RememberMe = model.RememberMe
});



回答2:


Try setting IsAuthenticated to true and saving your session...

public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
    base.OnAuthenticated(authService, session, tokens, authInfo);
    CustomFoo = "SOMETHING CUSTOM";
    session.IsAuthenticated = true;
    authService.SaveSession(session);

    // More stuff
}


来源:https://stackoverflow.com/questions/14835267/servicestack-session-always-null-in-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!