【发布时间】:2013-04-04 03:49:29
【问题描述】:
我目前有一个 IIS 托管应用程序,我想切换到使用自托管方法。
但我无法访问会话,因此我可以检索当前用户的用户名。
这是我在 IIS 下托管时使用的代码,效果很好:
/// <summary>
/// A basic wrapper for the service stack session, to allow access to it lower down in the DAL layer without tying us to servicestack.
/// </summary>
public class ServiceStackAuthTokenService : IAuthTokenService
{
/// <summary>
/// GetCurrentAuthToken.
/// </summary>
/// <returns>A string representing the users auth name.</returns>
public string GetCurrentAuthToken()
{
// Grab the current request.
var req = HttpContext.Current.Request.ToRequest();
var res = HttpContext.Current.Response.ToResponse();
// Fetch the authentication service.
var authService = EndpointHost.AppHost.TryResolve<AuthService>();
authService.RequestContext = new HttpRequestContext(req, res, null);
// Grab the session.
var session = authService.GetSession(false);
// Return the username.
return session.UserName;
}
public string UserPropertyName
{
get { return "UserName"; }
}
}
这是使用以下代码添加到应用程序主机的::
container.RegisterAutoWiredAs<ServiceStackAuthTokenService, IAuthTokenService>()
运行自托管时,HttpContext.Current 为空,如何在自托管应用程序下访问请求?
谢谢!
更新 我尝试过的其他事情:
根据这里的帖子:https://groups.google.com/forum/#!msg/servicestack/jnX8UwRWN8A/_XWzTGbnuHgJ
建议使用:
container.Register>(c => AuthService.CurrentSessionFactory);
这只是返回一个新的 IAuthSession。
该帖子中的用户正在做的正是我想要实现的目标。
Mythz 在上一篇文章中说:
需要明确的是,为了形成引用用户会话的会话密钥,您需要 ss-id 或 ss-pid cookie(由 ss-opts 确定)。 您可以从 IHttpRequest 对象或 ASP.NET 中的 HttpContext.Current.Request 单例中获取 cookie,因此无论您注入的任何 IAuthUserSession 工厂都需要获取可以为其提供 cookie 的东西,即 IRequestContext、IHttpRequest、IService 等。
但我仍然看不到访问 IHttpRequest 的方法。
【问题讨论】:
-
GetCurrentAuthToken() 何时/何地在您的应用程序中被调用?如果它在服务中,您可以将 IHttpRequest 和 IHttpResponse 传递给 GetCurrentAuthToken(base.Request, base.Response) 等方法。
-
您好 Paaschpa,它发生在与服务层没有直接关系的 DAL 层。我可以将上下文传递给 DAL,但这会违反设计并使每一层保持独立。
-
进一步研究后,我可以看到 IHttpRequest 和 IHttpResponse 正在通过服务基类中的 IRequiresRequestContext 接口注入到服务中。我基本上希望能够访问相同的东西,这样我就可以访问存储客户端会话的缓存。
-
使用反射器查看服务类我可以看到 if (this.userSession == null) { this.userSession = this.TryResolve
(); if (this.userSession == null) { this.userSession = this.Cache.SessionAs(this.Request, this.Response); } } return (TUserSession)((object)this.userSession);这段代码似乎表明,会话可以通过缓存访问。
标签: session authentication servicestack