I changed your code a bit since I do not have NullIdentity() , and your CurrentUserProvider did not compile here.
I installed these packages:
- Autofac
- Autofac.Owin
- Autofac.Owin
- Autofac.Mvc5
- Autofac.Mvc5.Owin
- Autofac.WebApi2
- Autofac.WebApi2.Owin
My Startup.cs looks like this:
public partial class Startup { public void Configuration(IAppBuilder app) { configureIoC(app); ConfigureAuth(app); } void configureIoC(IAppBuilder app) { var b = new ContainerBuilder();
Your ICurrentUser Material:
public interface ICurrentUser { Task <ApplicationUser> Get(); } public class CurrentUserProvider : ICurrentUser { private ApplicationUserManager users; private IIdentity currentLogin; public async Task<ApplicationUser> Get() { return await users.FindByNameAsync(currentLogin.GetUserId()); } public CurrentUserProvider(ApplicationUserManager users, IIdentity currentLogin) { this.users = users; this.currentLogin = currentLogin; } }
Therefore Global.asax:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
My HomeController , which is pretty simple:
public class HomeController : Controller { private ICurrentUser current; public HomeController(ICurrentUser current) { this.current = current; } public ActionResult Index() { var user = current.Get(); if (user == null) throw new Exception("user is null"); return View(); } }
... and finally, a simple ApiController, which I refer to by typing localhost / api / TestApi / 5 :
public class TestApiController : ApiController { private ICurrentUser current; public TestApiController(ICurrentUser current) { this.current = current; } public string Get(int id) { var user = current.Get(); if (user == null) throw new Exception("user is null"); return ""; } }
If I am just starting a project (without even logging in), I get a GenericIdentity object to support the IIdentity interface, look at this:

And when I find (F11) in the Get() method, IIdentity is set correctly using this GenericIdentity , because in fact no one is registered in the application. That's why I think you really don't need this NullableIdentity.

Try to compare your code with mine and fix yours so that we can see if it works, and then you will find out what was the real cause of the problem, and not just fix it (we developers love to know why something just got the job) .