Ninject和Asp.Net Web API依赖注入的问题

时间:2012-06-04 17:28:12

标签: asp.net ninject asp.net-web-api

我有一个ASP.NET web api项目与MVC3项目并排。对于这两个项目,Ninject被配置为依赖项解析器。

我在web api项目中遇到问题,因为我正在编写自己的Authorization属性,以便为我的API授权传入的请求。在这个属性中,我需要注入一些依赖项来对请求执行一些验证。

这就是属性中代码的外观:

public class CustomAuthorizeAttribute : ActionFilterAttribute 
{
    public string Roles { get; set; }

    [Inject]
    public IAuthSchemaSelector _schemaSelector { private get; set; }

    [Inject]
    public IUserService _userService { private get; set; }

    [Inject]
    public IRoleVerifier _roleVerifier { private get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        try
        {
            var principal = _schemaSelector.Authorize(actionContext.Request, Roles, _userService, _roleVerifier);
            actionContext.Request.Properties["MS_UserPrincipal"] = principal;
        }
        catch (Exception ex)
        {
            //create error response with proper http status
        }
    }
}

}

_schemaSelector决定客户端使用哪个授权模式来请求API中包含的服务(这是因为我计划支持不同的模式,如OAuth,API密钥授权等。现在我只是使用HttpBasic)。所以如果eveythign没问题,我设置了主要用户,所以我可以在ApiController中访问它。

一切都很完美,直到我从de MVC3项目(网站)进行修改。例如,网站中有一个功能,负责更改用户密码。假设你有一个初始密码123456.我使用HttpBasic从api发出请求,api响应http状态202。

现在我将密码从网站更改为1234567,使用旧密码(123456)从api执行另一个请求,它响应202,这是错误的。

_userService对象行为不正确(并且其他两个对象都没有注入),当我调试动作过滤器时,我注意到整个对象处于先前状态。我猜这是如何配置ninject的。

这就是我配置ninject的方式:

在NinjectWebCommon.cs中:

GlobalConfiguration.Configuration
            .ServiceResolver
            .SetResolver(t => kernel.TryGet(t),
                         t => kernel.GetAll(t));
ninject模块文件中的

kernel.Bind<IUserService>().To<UserService>(); //user service is part of the unit of work
kernel.Bind<IUnitOfWork>().To<EFUnitOfWork>().InRequestScope();
kernel.Bind<IRoleVerifier>().To<RoleVerifier>();
kernel.Bind<IAuthSchemaSelector>().To<AuthSchemaSelector>();

值得一提的是,我正在使用属性注入模式将_userService注入ActionFilterAttribute,因为我无法使用构造函数模式。我不知道这是不是问题。

请帮忙!我有点迷失在这里!

1 个答案:

答案 0 :(得分:0)

如何将CustomAuthorizeAttribute绑定到操作?它是全局过滤器还是基于每个操作?是您的服务/等。将状态存储在内存中?

不幸的是,这里没有很多信息可以帮助调试问题。也许您可以发布有关如何更改密码以及负责发回202响应等的更多信息?