2017-02-13 18 views
0

我在基於web api的項目中使用基於OAuth令牌的身份驗證。如何在Startup.cs中實例化此對象

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin"); 

     if (allowedOrigin == null) allowedOrigin = "*"; 

     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); 

     //At this line, I am getting Error Object reference not set. 
     if (_membershipService.ValidateUser(context.UserName.Trim(), context.Password.Trim())) 
     { 
      var user = _membershipService.GetUser(context.UserName); 

      /* db based authenication*/ 
      var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
      identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
      identity.AddClaim(new Claim(ClaimTypes.Role, "user")); 
      identity.AddClaim(new Claim("sub", context.UserName)); 

      var props = new AuthenticationProperties(new Dictionary<string, string> 
      { 
       { 
        "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId 
       }, 
       { 
        "userName", user.Email 
       }, 
       { 
        "role", (user.Role).ToString() 
       } 
      }); 

      var ticket = new AuthenticationTicket(identity, props); 
      context.Validated(ticket); 
     } 
     else 
     { 
      context.Rejected(); 
     } 


    } 

在呼籲_membershipService.ValidateUser(),我越來越不設置對象引用。這很明顯。

所以爲了解決這個錯誤,我將構造函數定義爲。

public SimpleAuthorizationServerProvider(IMembershipService membershipService) 
    { 
     _membershipService = membershipService; 
    } 

儘管調用方法,我傳遞的參考。

Startup.cs

public void ConfigureOAuth(IAppBuilder app) 
    { 
     OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
     OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() 
     { 
      //passing the membership object. 
      Provider = new SimpleAuthorizationServerProvider(_membershipService), 

     }; 

     // Token Generation 
     app.UseOAuthAuthorizationServer(OAuthServerOptions); 
     //Token Consumption 
     app.UseOAuthBearerAuthentication(OAuthBearerOptions); 




    } 

對象引用不設置爲一個對象的一個​​實例。

於是,我就超載Startup.cs的構造函數如下:

public Startup(IMembershipservice membership) 
{ 
    _membership = membership; 
} 

但是,這將引發此對象定義的下方運行時錯誤

無參數的構造函數。

Startup.cs

public Startup() 
    { 
     GlobalConfiguration.Configure(WebApiConfig.Register); 
     RegisterIOC(); 
    } 
private void RegisterIOC() 
    { 
     container = new WindsorContainer(); 
     container.Register(Component.For<SimpleAuthorizationServerProvider>().LifestyleTransient()); 
    //rest of the stuff 
    } 

如何instanitate Membership類。

(請注意我正在使用Castle Windsor DI容器)。

任何幫助/建議高度讚賞。 謝謝。

回答

1

您說您正在使用Castle Windsor DI容器,但沒有用於初始化Startup.cs類中的容器的代碼。 如果使用OWIN(Startup.cs類),則不需要Global.asax Application_Start方法中的應用程序初始化。 您應該將容器初始化移動到Startup.cs類並在初始化後解析IMembershipservice實例。 事情是這樣的:

public void Configuration(IAppBuilder app) 
    { 

     var container = new WindsorContainer().Install(new WindsorInstaller()); 
     container.Register(Component.For<IAppBuilder>().Instance(app)); 
     var httpDependencyResolver = new WindsorHttpDependencyResolver(container); 

     HttpConfiguration config = new HttpConfiguration(); 
     config.MapHttpAttributeRoutes(); 

     config.DependencyResolver = httpDependencyResolver; 
     GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorControllerActivator(container)); 


     app.UseWebApi(config); 
    } 

然後你可以用容器來解決你的類的實例。

+0

DI的東西是在不同的地方,我重新檢查,這一切的映射都到位。但仍然存在錯誤 –

+0

「DI東西在不同的地方」< - 這是錯誤的原因。 Startup.cs應該包含DI初始化。然後,您的Startup.cs類中有容器,可以解析您的類型。 – Salkony

+0

但是爲什麼只有這個類錯誤。所有控制器和服務正在實例化正確 –