Rty*_*ype 7 authentication session servicestack
我目前有一个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"; }
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码将其添加到应用主机::
container.RegisterAutoWiredAs<ServiceStackAuthTokenService, IAuthTokenService>()
Run Code Online (Sandbox Code Playgroud)
运行自托管时,HttpContext.Current为null,如何在自托管应用程序下访问请求?
谢谢!
更新 我尝试过的其他内容:
根据帖子:https://groups.google.com/forum/#!msg/servicestack/jnX8UwRWN8A/XWzTGbnuHgJ
有人建议使用:
container.Register>(c => AuthService.CurrentSessionFactory);
这只会返回一个新的IAuthSession.
该帖子中的用户正在做的正是我想要实现的目标.
在上一篇文章中,Mythz说:
为了清楚起见,为了形成引用Users会话的会话密钥,您需要ss-id或ss-pid cookie(由ss-opts确定).您可以从IHttpRequest对象中获取cookie,或者在ASP.NET中获取HttpContext.Current.Request单例,因此您注入的IAuthUserSession工厂需要采取可以为其提供cookie的内容,即IRequestContext,IHttpRequest,IService等.
但我仍然无法看到访问IHttpRequest的方法.
Rty*_*ype 10
对于ServiceStack 3,您可以通过HostContext.Instance.Items词典共享请求数据.对于ServiceStack 4,您应该使用HostContext.RequestContext.ItemsDictionary.
例如,在应用主机配置中添加请求过滤器以保存值:
// Put the session into the hostcontext.
RequestFilters.Add((req, res, requestDto) =>
{
HostContext.Instance.Items.Add("Session", req.GetSession());
});
Run Code Online (Sandbox Code Playgroud)
然后在您的身份验证令牌类中将其拉回:
public string GetCurrentAuthToken()
{
var session = HostContext.Instance.Items["Session"] as AuthUserSession;
if (session != null)
{
return session.UserName;
}
throw new Exception("No attached session found.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2102 次 |
| 最近记录: |