Asp.Net API 2 Ninject和OWIN OAuth配置 [英] Asp.Net API 2 Ninject and OWIN OAuth Configuration

查看:98
本文介绍了Asp.Net API 2 Ninject和OWIN OAuth配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多帖子与此相似.但是,我已经经历了他们,却无法找到解决我问题的方法.

I know there are many posts very similar to this one. However, I have been through them and have not been able to find a solution to my problem.

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

I am implementing OAth authentication using OWIN into a previous project which utilises Ninject for dependency injection.

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

To implement OATH using OWIN switched from the original Global.asax Application_Start configuration method to creating a Start.cs file/class which is used to configure OWIN.

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

The problem I am facing is that no matter what implementation I try upon running the code, an API request always returns the error "Make sure that the controller has a parameterless public constructor".

请有人能阐明为什么以下两种方法都行不通吗?

Please can some one shed some light on why neither of the below approaches work?

我解决该问题的第一个尝试是将app.UseNinjectMiddleware与app.UseNinjectWebApi一起使用.其次,我尝试了NinjectDependencyResolver,这在以前的许多文章中都提到过.链接到类似帖子.

My first attempt at resolving the issue was to use app.UseNinjectMiddleware with app.UseNinjectWebApi. Secondly I tried a NinjectDependencyResolver which has been mentioned on many previous posts. Link to similar post.

下面是继续执行这两种代码的代码.

Below is the code contining both implementations.

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类

Here is my NinjectWebCommon class

//[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 )
        {
        }
    }
}

感谢进阶

推荐答案

我终于解决了这个问题,解决方案是使用Ninject.Web.Common库随附的原始NinjectWebCommon类.此类的启动方法在Startup.Configuration之前触发,因此可以与此

I finally solved the problem, the solution was to use the original NinjectWebCommon class that came with the Ninject.Web.Common library. This class's start method fires before Startup.Configuration so can be used with this Dependency Resolver by retiring it through the bootstrapper. Here is my working 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 );
    }

这篇关于Asp.Net API 2 Ninject和OWIN OAuth配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆