【发布时间】:2012-12-24 12:33:02
【问题描述】:
我想在我的 ApiController (MVC4) 中拥有自己的 AppContext。
应该是这样的
public class TestController : BaseApiController
{
[HttpGet]
public IEnumerable<TestVM> GetAll()
{
// the test service is injected with SimpleInjector
return _testService.GetAll(**base.AppContext**);
}
}
但 ApiController 无法访问 Session。 是否有任何解决方案可以“激活”特定键的会话(因为我不想要整个会话)? 或者您有什么其他想法(缓存或 cookie)?
这是 BaseApiController
public abstract class BaseApiController: ApiController
{
public IAppContext AppContext
{
get { return SessionState.AppContext; }
}
}
这是我的 IAppContext(以后会有更多的属性)
public interface IAppContext
{
IIdentity User { get; }
/// <summary> Gets the user id. </summary>
/// <value>The user id.</value>
int IdUser { get; }
}
这里是web.config中注册的应用模块
public class ApplicationModule : IHttpModule
{
// ...
SessionState.AppContext = _appContext.InitializeNew(
HttpRuntime.AppDomainAppPath, languages);
// ...
}
SessionState 类获取 AppContext
public class SessionState : BaseSessionVariables
{
public static IAppContext AppContext
{
get { return SessionState.Get<IAppContext>("AppContext"); }
set { SessionState.Set("AppContext", value); }
}
}
这里是 BaseSessionVariables 类
public static HttpSessionState GetSession()
{
return HttpContext.Current.Session;
}
protected static T Get<T>(string key) where T : class
{
var session = BaseSessionVariables.GetSession();
if (session == null)
{
throw new Exception("No session");
}
return (session[key] as T);
}
感谢您的帮助!
【问题讨论】:
标签: asp.net-mvc-4 controller session-state