2013-04-12 25 views
1

我正在使用ASP.NET MVC 4Autofac。我有一個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

+0

您使用的是什麼樣的身份驗證? Windows,窗體等? – nemesv

+0

Windows。我有我的web.config中的Windows身份驗證模式,但它仍然是空的。我只有'' –

+0

請參閱下面的答案。 –

回答

1

該網站使用Visual Studio 2012附帶的IIS。我不知道我需要禁用匿名身份驗證並在Web項目本身上啓用Windows身份驗證。它現在有效。下面是我跟着如果任何一個人有同樣的問題的步驟:在Solution Explorer中的項目

IIS快遞

  • 單擊以選中的項目。
  • 如果「屬性」窗格未打開,請將其打開(F4)。
  • 在爲您的項目屬性面板:

    • 集「匿名身份驗證」改爲「已禁用」。
    • 將「Windows身份驗證」設置爲「已啓用」。