我在我的一个项目中使用ServiceStack作为基础库。
我将我的应用程序分为API和WEB应用程序,它们是分开的项目和存储库。
身份验证应该在API层进行,并且应该在那里缓存。我在API服务器中使用Ormlite缓存客户端。
在API AppHost.cs文件中:
var dbFactory = new OrmLiteConnectionFactory("ConnectionString",SqlServerDialect.Provider);
container.RegisterAs<OrmLiteCacheClient, ICacheClient>();
container.Resolve<ICacheClient>().InitSchema();
Plugins.Add(new AuthFeature(() => new APISession(),
new IAuthProvider[] {
new APICredentialsAuthProvider(new AppSettings())
}));
在 APICredentialsAuthProvider 中,我保存了会话,并将其存储在 CacheEntry 表中。
通过 ajax 调用 apiurl/auth 对用户进行身份验证,在返回的 AuthenticateResponse 中带有 sessionId。 我将此 sessionId 更新为 cookie 的 s-id,并在预请求过滤器中根据请求类型更新为 ss-id 或 ss-pid。
//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
System.Net.Cookie cookie = req.Cookies["s-id"];
req.Cookies["ss-id"] = cookie;
req.SetSessionId(cookie.Value)
});
这种方法并不会从缓存中获取会话,我在使用Ormlite和Web和Api应用程序中提供了相应的配置。
那么,最好的方法是什么?
然而,我可以通过使用缓存客户端来访问会话。
//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
System.Net.Cookie cookie = req.Cookies["s-id"];
req.Cookies["ss-id"] = cookie;
req.SetSessionId(cookie.Value);
APISession cachedSession = GetCacheClient(req).Get<APISession(SessionFeature.GetSessionKey(cookie.Value));
WEBSession session.PopulateWith<WEBSession, APISession>(cachedSession);
});
这个方案的运行很好,我可以获取会话,但是将其放在预请求过滤器中会增加 Web 应用程序对数据库的调用(每个请求都要调用一次)。
有没有其他可用的方案来实现同样的效果呢?
提前致谢!