我目前有一个托管在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的方法。