Asp.Net API 2 Ninject and OWIN OAuth Configuration

本文关键字:OWIN OAuth Configuration and Ninject Net API Asp | 更新日期: 2023-09-27 18:26:56

我知道有很多帖子与这篇非常相似。然而,我经历了这些,一直没能找到解决我问题的办法。

我在以前的一个项目中使用OWIN实现OAth身份验证,该项目使用Ninject进行依赖项注入。

要使用OWIN实现OATH,请从最初的Global.asax Application_Start配置方法切换到创建用于配置OWIN的Start.cs文件/类。

我面临的问题是,无论我在运行代码时尝试什么实现,API请求总是返回错误"确保控制器具有无参数的公共构造函数"。

请有人解释一下为什么以下两种方法都不起作用?

我第一次尝试解决这个问题是使用应用程序。将NinjectMiddleware与应用程序一起使用。使用NinjectWebApi。其次,我尝试了一个NinjectDependencyResolver,它在以前的许多帖子中都提到过。链接到类似的帖子。

下面是两种实现的代码。

public class Startup
{
    public void Configuration( IAppBuilder app )
    {
        var config = new HttpConfiguration();
        var kernel = NinjectWebCommon.CreateKernel();
        // Using this and UseNinjectWebAPI
        app.UseNinjectMiddleware( () => kernel );
        ConfigureOAuthTokenGeneration( app );
        ConfigureWebApi( config );
        app.UseCors( Microsoft.Owin.Cors.CorsOptions.AllowAll );
        WebApiConfig.Register( config );
        app.UseNinjectWebApi( config );
        // Also tried this ( when the following lines are uncommented UseNinjectMiddleware and useNinjectWebApi is commented )
        // This causes "Make sure that the controller has a parameterless public constructor" error
        //GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver( kernel );
        //app.UseWebApi( config );
    }
    private void ConfigureOAuthTokenGeneration( IAppBuilder app )
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext( ApplicationDbContext.Create );
        app.CreatePerOwinContext<ApplicationUserManager>( ApplicationUserManager.Create );
        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
    }
    private void ConfigureWebApi( HttpConfiguration config )
    {
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

这是我的NinjectWebCommon类

//[assembly:     WebActivatorEx.PreApplicationStartMethod(typeof(TimeUp.Web.Api.App_Start.NinjectWebCommon), "Start")]
//[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(TimeUp.Web.Api.App_Start.NinjectWebCommon), "Stop")]
namespace Shopping
{
    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();
        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule( typeof( OnePerRequestHttpModule ) );
            DynamicModuleUtility.RegisterModule( typeof( NinjectHttpModule ) );
            bootstrapper.Initialize( CreateKernel );
        }
        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        public static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod( ctx => () => new Bootstrapper().Kernel );
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
                RegisterServices( kernel );
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices( IKernel kernel )
        {
        }
    }
}

感谢先进的

Asp.Net API 2 Ninject and OWIN OAuth Configuration

我终于解决了这个问题,解决方案是使用Ninject.Web.Common库附带的原始NinjectWebCommon类。此类的start方法在Startup之前激发。通过引导程序将其引退,可以将Configuration与此依赖关系解析程序一起使用。这是我的工作配置。

    public void Configuration( IAppBuilder app )
    {
        var config = new HttpConfiguration();
        config.DependencyResolver = new NinjectResolver( new Ninject.Web.Common.Bootstrapper().Kernel );
        WebApiConfig.Register( config );
        app.UseWebApi( config );
    }