【问题标题】:Ninject Troubles getting UserName from WebContextNinject 从 WebContext 获取用户名的麻烦
【发布时间】: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


    【解决方案1】:

    在服务层和存储库层中直接访问System.Web.HttpContext 不是一个好习惯,因为很难对您的项目进行单元测试。

    相反,您想通过构造函数注入 HttpContextBase。

    public class ServiceContext : IServiceContext
    { 
       HttpContextBase _httpContextBase,
    
       public ServiceContext(HttpContextBase httpContextBase)
       {
          _httpContextBase = httpContextBase;
       }
    }
    

    然后像这样访问用户-

    string username = _httpContextBase.User.Identity.Name;
    

    【讨论】:

    • 您好,感谢您的回复,但没有解决问题。尝试了您的代码,但它与上面的错误相同。有时 httpContextBase.User == null,虽然我之前登录过。
    • 没有看到你是如何创建 Principal 对象的,我不能说出了什么问题。 注意:您不能在用户登录的同一请求中访问HttpContext.Current.User。看看这个answer
    • 对不起,你的答案是正确的,但我做错了。试图在构造函数中读取用户名,但是当我从属性 Username 它的工作中访问我的 getter 中的用户时,这是失败的^^。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2019-08-08
    • 2017-09-23
    • 1970-01-01
    相关资源
    最近更新 更多