gpt4 book ai didi

asp.net-mvc-4 - 为 ApiController 使用 session 状态

转载 作者:行者123 更新时间:2023-12-02 05:18:27 26 4
gpt4 key购买 nike

我想在我的 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 的权限。是否有任何解决方案可以为特定键“激活” session (因为我不想要整个 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);
// ...
}

获取AppContext的SessionState类

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);
}

感谢您的帮助!

最佳答案

看看下面的实现。它应该让你朝着正确的方向前进。

更新的 IAppContext - 添加了 setter

public interface IAppContext
{
IIdentity User { get; set; }

/// <summary> Gets the user id. </summary>
/// <value>The user id.</value>
int IdUser { get; set; }
}

更新的基础 Controller - 在 OnActionExecuting 方法中实例化一个新的 AppContextImplemenation

public abstract class BaseApiController: ApiController
{
public IAppContext AppContext {get; set;}

protected override void OnActionExecuting(
ActionExecutingContext filterContext)
{
AppContext = new AppContextImplementation();
}
}

新类 - 实现 IAppContext 并包装 HttpContext session 。为了进行测试,您可以创建一个 TestAppContextImplementation,它不依赖于 Session,而是依赖于其他一些内存存储机制。

public class AppContextImplementation : IAppContext
{
public IIdentity User
{
get { return HttpContext.Current.Session["User"] as IIdentity; }
set { HttpContext.Current.Session["User"] = value; }
}

int IdUser
{
get { return Convert.ToInt32(Session["IdUser"]); }
set { Session["IdUser"] = value; }
}
}

关于asp.net-mvc-4 - 为 ApiController 使用 session 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14252544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com