How exactly IAppBuilder.CreatePerOwinContext should be used?

后端 未结 2 2013
慢半拍i
慢半拍i 2020-12-19 07:17

I\'m confused on how the OWIN CreatePerOwinContext method is to be used. As far as I can see it\'s a poor mans DI mechanism. Yet, I fail to see how to use it.

We can

相关标签:
2条回答
  • 2020-12-19 07:30

    I have a more correct answer after running into this myself, trying to implement the code within this stackoverflow answer: https://stackoverflow.com/a/31918218

    So given this initialization code within the conventional Configure method:

    static void Configuration(IAppBuilder app)
    {
        //https://stackoverflow.com/a/31918218
        app.CreatePerOwinContext<AppBuilderProvider>(() => new AppBuilderProvider(app));
    
        ConfigureAuth(app); //note implementation for this is typically in separate partial class file ~/App_Start/Startup.Auth.cs
    }
    

    One can retrieve the instance created by this code:

    public ActionResult SomeAction() 
    {
        //https://stackoverflow.com/a/31918218
        var app = HttpContext.GetOwinContext().Get<AppBuilderProvider>("AspNet.Identity.Owin:" + typeof(AppBuilderProvider).AssemblyQualifiedName).Get();
        var protector = Microsoft.Owin.Security.DataProtection.AppBuilderExtensions.CreateDataProtector(app, typeof(Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
        var tdf = new Microsoft.Owin.Security.DataHandler.TicketDataFormat(protector);
        var ticket = new AuthenticationTicket(ci, null);
        var accessToken = tdf.Protect(ticket);
    
        //you now have an access token that can be used.
    }
    
    0 讨论(0)
  • 2020-12-19 07:33

    You can use typeof to get the key parameter:

    HttpContext.GetOwinContext().Get<ApplicationDbContext>(typeof(ApplicationDbContext).ToString());
    

    Also, Microsoft.AspNet.Identity.Owin assembly contains the parameterless version of Get<T>() method, so you can use it if you already have ASP.NET Identity in your project.

    0 讨论(0)
提交回复
热议问题