我正在使用ASP.NET MVC 4
和Autofac
。我有一个WebWorkContext
课程,我在我的解决方案的各个地方注入,以获得当前员工的详细信息。
以下是我的global.asax文件中的Autofac注册:
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
。
答案 0 :(得分:1)
该网站使用Visual Studio 2012附带的IIS。我不知道我需要禁用匿名身份验证并在Web项目本身上启用Windows身份验证。它现在有效。如果其他任何人遇到同样的问题,我会遵循以下步骤:
IIS Express
在项目的“属性”窗格中: