首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尼尼特故障从UserName获得WebContext

尼尼特故障从UserName获得WebContext
EN

Stack Overflow用户
提问于 2013-09-17 10:36:54
回答 1查看 363关注 0票数 0

嗨,我在网站上遇到麻烦了。有时在登录我的网站重定向到登录页说我没有权利使用这个功能,请登录。

好的,首先我想,我的访问权限出了点问题,但那不是,如果我回到浏览器中的一个站点并再次发送请求,它就能工作了。

所以我对它进行了调试,经过大量的测试,我得到了一个结果,当我用with创建服务上下文时,UserName是一个空字符串。

这是我的代码:首先,我的接口IServiceContext:

代码语言:javascript
复制
public interface IServiceContext
{
    string UserName { get; }
}

然后是类ServiceContext:

代码语言:javascript
复制
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);
    }
}

我的绑定设置在一个单独的文件中,如下所示:

代码语言:javascript
复制
Bind<SecurityManagement >().ToSelf().InTransientScope();
Rebind<IServiceContext>().To<ServiceContext>().InRequestScope();

我需要使用rebind,因为在我的框架中生成了一个用于StandardBinding的serviceContext。

我的InvokeMethod的电话:

代码语言:javascript
复制
class SecurityManagement : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        IServiceContext _context = _kernel.Get<IServiceContext>();
        String name = System.Web.HttpContext.Current.User.Identity.Name;
    }
}

所以有时候,我的_context.UserName是一个空字符串。我发现当n注入到System.Web.HttpContext.Current.User.Identity.Name时,ServiceContext属性是一个空字符串,但是变量名具有正确的用户名。对于我来说,没有办法让属性UserName的设置器成为我正在使用的框架的公共原因。

有人知道为什么会发生这种事吗?也许有什么办法解决这个问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-18 15:35:20

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

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

代码语言:javascript
复制
public class ServiceContext : IServiceContext
{ 
   HttpContextBase _httpContextBase,

   public ServiceContext(HttpContextBase httpContextBase)
   {
      _httpContextBase = httpContextBase;
   }
}

然后像这样访问用户-

代码语言:javascript
复制
string username = _httpContextBase.User.Identity.Name;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18847570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档