【发布时间】:2013-09-17 10:36:54
【问题描述】:
您好,我在使用网站时遇到问题。有时登录后,我的网站会将我重定向到登录页面,说我无权使用此功能,请登录。
好吧,首先我想,我的访问权限有问题,但事实并非如此,如果我只是返回浏览器中的一个站点并再次发送请求,它就可以工作。
所以我对其进行了调试,经过大量测试后发现,当我使用 Ninject 创建服务上下文时,用户名是一个空字符串。
这是我的代码: 首先是我的接口 IServiceContext:
public interface IServiceContext
{
string UserName { get; }
}
然后是类ServiceContext:
public class ServiceContext : IServiceContext
{
private static Object _syncRoot = new Object();
private static long _instance = 0;
private long _currentInstance = 0;
public string UserName { get; private set; }
public ServiceContext()
{
lock (_syncRoot)
{
if (_instance >= long.MaxValue)
_instance = 0;
_currentInstance = _instance++;
}
if (System.Web.HttpContext.Current.User == null)
UserName = "";
else
UserName = System.Web.HttpContext.Current.User.Identity.Name;
}
public ServiceContext(string userName)
{
UserName = userName;
}
public override string ToString()
{
return string.Format("#{0}, UserName: {1}", _currentInstance, UserName);
}
}
我的绑定设置在一个单独的文件中,如下所示:
Bind<SecurityManagement >().ToSelf().InTransientScope();
Rebind<IServiceContext>().To<ServiceContext>().InRequestScope();
我需要使用重新绑定,因为在我的框架中为 serviceContext 创建了一个 StandardBinding。
还有来自我的 InvokeMethod 的调用:
class SecurityManagement : IInterceptor
{
public void Intercept(IInvocation invocation)
{
IServiceContext _context = _kernel.Get<IServiceContext>();
String name = System.Web.HttpContext.Current.User.Identity.Name;
}
}
所以有时会发生,我的 _context.UserName 是一个空字符串。我发现 System.Web.HttpContext.Current.User.Identity.Name 属性在注入 ServiceContext 时是一个空字符串,但变量名称具有正确的用户名。我无法将 Property UserName 的设置器设为我正在使用的框架的公共原因。
所以有人知道为什么会这样吗?也许有任何解决问题的想法
【问题讨论】:
标签: c# asp.net-mvc dependency-injection ninject httpcontext