1
我正在使用ASP.NET MVC 4
和Autofac
。我有一個WebWorkContext
班,我在我的解決方案的各個地方注入以獲取當前員工的詳細信息。使用autofac時,User.Identity.Name爲空AutofacWebTypesModule
這是我Autofac登記在我的Global.asax文件:
protected void Application_Start()
{
// Autofac
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
我WebWorkContext類:
public class WebWorkContext : IWorkContext
{
private readonly IEmployeeService employeeService;
private readonly HttpContextBase httpContext;
public WebWorkContext(IEmployeeService employeeService, HttpContextBase httpContext)
{
this.employeeService = employeeService;
this.httpContext = httpContext;
}
public Employee CurrentEmployee
{
get
{
return GetCurrentEmployee();
}
}
protected Employee GetCurrentEmployee()
{
string identityName = this.httpContext.User.Identity.Name.ToLower();
// Do what I need to do to get employee details from
// the database with identityName
}
}
我把一個破發點上:
string identityName = this.httpContext.User.Identity.Name.ToLower();
identityName
總是空的。不知道爲什麼?我錯過了什麼嗎?
我如何使用WebWorkContext類:
public class CommonController : Controller
{
private readonly IWorkContext workContext;
public CommonController(IWorkContext workContext)
{
this.workContext = workContext;
}
public ActionResult EmployeeInfo()
{
Employee employee = workContext.CurrentEmployee;
EmployeeInfoViewModel viewModel = Mapper.Map<EmployeeInfoViewModel>(employee);
return PartialView(viewModel);
}
}
我使用Visual Studio 2012
。
您使用的是什麼樣的身份驗證? Windows,窗體等? – nemesv
Windows。我有我的web.config中的Windows身份驗證模式,但它仍然是空的。我只有' authentication>' –
請參閱下面的答案。 –