我有一个班级
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://cloud.estimote.com/v1/beacons');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$appid:$token");
$output = curl_exec($ch);
curl_close($ch);
这个类的一个实例被注入我的控制器,如下所示:
Startup.cs
public class SessionService : ISessionService
{
public const string SessionUserKey = "UserViewModel";
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
public SessionService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public UserViewModel LoggedInUser
{
get
{
return _session.GetObjectFromJson<UserViewModel>(SessionUserKey);
}
set
{
_session.SetObjectAsJson(SessionUserKey, value);
}
}
public void Destroy()
{
_session.Clear();
}
}
AccountController.cs
services.AddScoped<ISessionService, SessionService>();
但是,在我看来,我想要访问当前登录的用户:
public class AccountController : Controller
{
private readonly IUserAccountService _accountService;
private readonly ISessionService _sessionService;
public AccountController(IUserAccountService accountService, ISessionService sessionService)
{
_accountService = accountService;
_sessionService = sessionService;
}
}
如何在不使 @if(SomeClass.LoggedInUser != null){
// code removed for brevity
}
类的LoggedInUser
属性静态的情况下实现此目的。似乎有些东西需要我做一个像这样的访问静态。但我想知道是否有更好的方法来实现这一目标。不,我不想使用SessionService
。
我没有使用ASP.Net Identity
答案 0 :(得分:3)
如果您想使用DI在视图中注入服务,则应使用@inject
@inject WebProject.Services.ISessionService CurrentSessionService
@if (CurrentSessionService.LoggedInUser != null)
{
// ...
}