我正在尝试使用与MyApp.Core
模块完美配合的MyApp.Application
,MyApp.EntityFramework
和MyApp.Web
模块来实现命令行应用程序。
MyApp.Console
应用程序的问题是登录:执行登录后,AbpSession
值仍为null
,因此,当我调用受任何权限保护的服务时,它返回我用户未通过身份验证。
这里是代码:
var result = await _logInManager.LoginAsync("myuser", "mypassword "mytenant", true);
if (result.Result != AbpLoginResultType.Success) throw new AbpAuthorizationException(result.Result.ToString());
// *** WHY AbpSession.TenantId and AbpSession.UserId are still null here?
ClaimsAbpSession
,IAbpSession
的默认实现,从当前用户的委托人的声明中获取会话属性,通常在调用_signInManager.SignInAsync(...)
之后在(web)响应中设置这些属性。
要在TenantId
之后获得UserId
和_logInManager.LoginAsync(...)
,可以使用loginResult.User.TenantId
和loginResult.User.Id
。
您还可以使用登录用户覆盖当前会话值:
var loginResult = await _logInManager.LoginAsync(...);
if (loginResult.Result != AbpLoginResultType.Success) throw new AbpAuthorizationException(...)
using (AbpSession.Use(loginResult.User.TenantId, loginResult.User.Id))
{
// AbpSession.TenantId and AbpSession.UserId now return the logged-in user's values.
}
参考:https://aspnetboilerplate.com/Pages/Documents/Abp-Session#overriding-current-session-values
受Aaron's answer的启发,我决定创建我的IAbpSession
实现。
为此,我只是将TestAbpSession
中可用的here克隆到脏的MyAbpSession
中。然后,在MyApp.Console模块中将其配置为默认IAbpSession
。
这里是代码:
[DependsOn(
typeof(MyAppApplicationModule),
typeof(MyAppDataModule))]
public class MyConsoleAppModule : AbpModule {
public override void PreInitialize() {
// set my IAbpSession implementation
Configuration.IocManager.RegisterIfNot<IAbpSession, MyAbpSession>(DependencyLifeStyle.Singleton);
}
public override void Initialize() {
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
并且在应用程序类中:
public class AppMain : ITransientDependency {
public MyAbpSession AbpSession { get; set; }
public AppMain() {
// What to set here?
//AbpSession = NullAbpSession.Instance;
}
// code to login
private async Task Login(userName: string, password: string, tenantName: string) {
var result = await _logInManager.LoginAsync(username, password, tenantName, false);
if (result.Result != AbpLoginResultType.Success) throw new AbpAuthorizationException(result.Result.ToString());
AbpSession.TenantId = result.User.TenantId;
AbpSession.UserId = result.User.Id;
}
public async Task Run(AppOptions options) {
await Login(options.userName, options.password, options.TenantName)
// my code ...
}
}