How to used ServiceStack UserSession In the View?

I used the ServiceStack.Mvc in the asp.net mvc application.

  public class HomeController : ServiceStackController<CustomUserSession>
    {
        public ActionResult Index()
        {
             return View();
        }
    }

I don’t use ServiceStack.Razor, But want the view have the inherits ServiceStack.Razor.ViewPage function. So I changed the index.cshtml like this

@using ServiceStack
@using ServiceStack.Host.AspNet
@{
    using (var provider =
            new ServiceStackProvider(new AspNetRequest(Context, GetType().Name)))
    {
        var session = provider.SessionAs<CustomUserSession>();
        if (provider.IsAuthenticated)
        {
           ...
        }
        else
        {
            ...
        }
    }
} 

The Question is my code will generate problem? Is there any good way to fulfill like it ?

You shouldn’t create a new instance of ServiceStackProvider directly.
To get the UserSession in a ServiceStack.Razor View you can just use:

@{
var userSession = base.SessionAs<CustomUserSession>();
}

But I don’t to use the ServiceStack.Razor View, I only use the asp.net mvc default view, how to get it ?

From the ServiceStackController, Pass it into the ViewModel.

Thanks! If I use ViewData, Like this

  public class ServiceStackControllerBase : ServiceStackController<CustomUserSession>
    {
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            base.OnAuthentication(filterContext);
            ViewData["provider"] = base.ServiceStackProvider;
        }
}

and in .cshtml like this

@{
    var provider = ViewData["provider"] as IServiceStackProvider;  
    var session = provider.SessionAs<CustomUserSession>();
}

If I used ViewData to Transfer the ServiceStackProvider, Is there any limit or any resource will not GC ?

Yeah that’s fine, you’re just passing a reference to the existing Provider instance, it’s not expensive at all.

@ali:

I’ve been doing the following for a long time in my main _Layout.cshtml (to display username in nav bar, etc). It doesn’t require anything controller-side with ViewData…

@{
    var session = AppHost.Instance.Resolve<ServiceStack.Caching.ICacheClient>().Get<CustomUserSession>(SessionFeature.GetSessionKey() ?? "");
}

Not sure how this compares performance-wise to what you’re doing. Maybe @mythz has a thought on that.

@robertmiles3 it’s close to doing the same thing but your example wont work in self-hosts since you’re not passing in a ServiceStack IRequest in GetSessionKey(IRequest) and only ASP.NET hosts can get it from the HttpContext.Current singleton.

Gotcha. I’m not self-hosting so I’ve never hit that. :slight_smile: