我正在使用ASP.NEt MVC 5 WEBAPI 2.2开发应用程序,其中OWIN + Identity与Autofac, 我在调用API控制器的方法时收到错误 HttpAuthenticationContext.Request不能为空。。 API控制器构造函数被调用但方法不是。 以下是我的文件。
Global.asx
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
IocConfig.RegisterDependencies();
LogConfig.RegisterLog4NetConfig();
// DataBaseConfig.Initialize();
//var dbContext = new GoSphereDataContext();
// Database.SetInitializer<GoSphereDataContext>(new GoSphereInitializer(dbContext));
//var dbContext = new GoSphereDataContext();
//if (!dbContext.Database.Exists())
//{
// dbContext.Database.Create();
//}
}
}
IocConfig.cs
/// <summary>
/// Inject Dependencies which are registered here with Container Builder.
/// </summary>
public class IocConfig
{
public static void RegisterDependencies()
{
ContainerBuilder containerBuilder = new ContainerBuilder();
// Register all controllers.
containerBuilder.RegisterControllers(typeof(HomeController).Assembly);
// Register all API controllers.
containerBuilder.RegisterApiControllers(typeof(PackageController).Assembly);
// Register HttpContextBase.
containerBuilder.RegisterType(typeof(HttpContextBase));
// Register Libs.
containerBuilder.RegisterAssemblyTypes(typeof(PackageLib).Assembly).Where(t => t.Name.EndsWith("Lib")).InstancePerLifetimeScope();
// Register other dependencies.
containerBuilder.RegisterType<GoSphereDataContext>().As<DbContext>().InstancePerDependency();
containerBuilder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();
containerBuilder.RegisterGeneric(typeof(DataRepository<>)).As(typeof(IDataRepository<>)).InstancePerDependency();
IContainer container = containerBuilder.Build();
// Create the depenedency resolver for Web API.
var resolver = new AutofacWebApiDependencyResolver(container);
// Set MVC DI resolver to use our Autofac container
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;
GlobalUtil.LifeTimeComponentContext = container;
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
MeController.cs
[Authorize]
public class MeController : BaseApiController
{
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
// GET api/Me
public GetViewModel Get()
{
var user = UserManager.FindById(User.Identity.GetUserId<int>());
return new GetViewModel() { Name = user.Name };
}
public MeController(ILifetimeScope lifetimeScope)
: base(lifetimeScope)
{
}
}
在调用domain / api / me时, controller get方法的构造函数,在调用之前,其Get方法会出错
任何人都可以帮助我吗?
答案 0 :(得分:2)
解决问题。
在BaseApiController中,我覆盖了Initialize Method并忘记调用base.Initialize();
就是它解决了这个问题。