嗨,我在网站上遇到麻烦了。有时在登录我的网站重定向到登录页说我没有权利使用这个功能,请登录。
好的,首先我想,我的访问权限出了点问题,但那不是,如果我回到浏览器中的一个站点并再次发送请求,它就能工作了。
所以我对它进行了调试,经过大量的测试,我得到了一个结果,当我用with创建服务上下文时,UserName是一个空字符串。
这是我的代码:首先,我的接口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();我需要使用rebind,因为在我的框架中生成了一个用于StandardBinding的serviceContext。
我的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是一个空字符串。我发现当n注入到System.Web.HttpContext.Current.User.Identity.Name时,ServiceContext属性是一个空字符串,但是变量名具有正确的用户名。对于我来说,没有办法让属性UserName的设置器成为我正在使用的框架的公共原因。
有人知道为什么会发生这种事吗?也许有什么办法解决这个问题
发布于 2013-09-18 15:35:20
直接访问服务层和存储层中的System.Web.HttpContext并不是一个好的实践,因为很难对项目进行单元测试。
相反,您希望通过构造函数注入HttpContextBase。
public class ServiceContext : IServiceContext
{
HttpContextBase _httpContextBase,
public ServiceContext(HttpContextBase httpContextBase)
{
_httpContextBase = httpContextBase;
}
}然后像这样访问用户-
string username = _httpContextBase.User.Identity.Name;https://stackoverflow.com/questions/18847570
复制相似问题