Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get HttpContext.Current.GetOwinContext() in startup

I very read for this problem but i can not fixed this so i think create a new question in this site.

HttpContext.Current.GetOwinContext();

i want get GetOwinContext values with above code . above code there are in my startup.cs

[assembly: OwinStartupAttribute(typeof(OwinTest.Startup))]

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        var c = HttpContext.Current.GetOwinContext();
    }
}

and i get this error

//No owin.Environment item was found in the context

but var c = HttpContext.Current.GetOwinContext(); work for me in HomeController fine.!

I just get GetOwinContext in my startup.cs class.

thankfull

like image 601
Amin Saadati 2 Avatar asked Jul 15 '16 10:07

Amin Saadati 2


2 Answers

You can't do that. The OWIN context does not exist without a request, and the Startup class only runs once for the application, not for each request. Your Startup class should initialize your middleware and your application and the middleware and the application should access the OWIN context when needed.

like image 136
MichaelDotKnox Avatar answered Sep 25 '22 18:09

MichaelDotKnox


As mentioned, what you are asking isn't possible. However, depending on your requirements, the following is possible and gives you access within the context of creating object instances. This is something I needed in order to check for whether an instance was already added else where (I have multiple startup classes in different projects).

public void Configuration(IAppBuilder app)
{
     ConfigureAuth(app);

     // Ensure we have our "main" access setup
     app.CreatePerOwinContext<DataAccessor>(
            (options, owinContext) => 
            {
                // Check that an instance hasn't already been added to
                // the OwinContext in another plugin
                return owinContext.Get<DataAccessor>() ?? DataAccessor.CreateInstance(options, owinContext);
            }
        );
}

Within the CreatePerOwinContext we have access to the OwinContext, so we can access it at the point of creating a new type. This might not help everyone as it's a little more specific to a person's needs, but is useful to know.

like image 20
JDandChips Avatar answered Sep 25 '22 18:09

JDandChips