1

I want to find an equivalent to the HttpContext.Application Property but using OWIN. I'm not looking for the equivalent of HttpContext in OWIN because I already know what is it, I need to know what's the exactly equivalent of the Application property.

What I want to do is to create an object at the startup, use it on some request to Web API without recreating the object again so I want to have it in memory.

I'm using: - .Net 4.5 - ASP.NET Web API 2.2 - Microsoft.Owin.Host.SystemWeb 3.0.1

I've searched on Google and StackOverflow and found that I should use the CreatePerOwinContext method but I don't know how to get the value I set into the context when I get requests from the clients on Web API.

In the old ASP.NET host I used to use this:

var myVariable = HttpContext.Application["MyVariable"]

  • possible duplicate of [Alternative to use HttpContext in System.Web for Owin](http://stackoverflow.com/questions/24572794/alternative-to-use-httpcontext-in-system-web-for-owin) – tukaef Jul 15 '15 at 16:44
  • @2kay thank you but that question doesn't solve my question. I'm asking for an equivalent to the `HttpContext.Application` and how to get the value from it usin OWIN and the question you are talking about just say how to use it for authentication. – Ernesto Gutierrez Jul 15 '15 at 22:48

1 Answers1

2

If you used CreatePerOwinContext to create the instance myVariable of type myType then you should be able to use something like the following:

HttpContext.GetOwinContext().Get<MyType>()

The return will be myVariable or the default return value if not present.

See: https://msdn.microsoft.com/en-us/library/dn270631(v=vs.113).aspx

Note however, that CreatePerOwinContext is still creating a new instance of the specified object per request, so you will need to figure out a way to pass your in-memory instance of MyType as part of the static Create method called by CreatePerOwinContext.

Or, you could set a public instance on the WebApiApplication class in Global.asax during the call to Application_Start() and then just grab it when needed, but that's a little... eew.

XIVSolutions
  • 4,442
  • 19
  • 24
  • It seems that CreatePerOwinContext is not the better solution for what I need so I will look for another solution. But I want to ask you something, HttpContext.GetOwinContext().Get() needs a key parameter but when creating the CreatePerOwinContext it doesn't ask for the key, just for a creating method so where can I set the key? Thanks. – Ernesto Gutierrez Jul 21 '15 at 21:54
  • `CreatePerOwinContext` is used with a static method which returns an instance of the type you are looking for. For an example, look at how the basic ASP.NET project with Identity uses `CreatePerOwinContext` in `Startup_Auth`, and then find the static `Create` method defined on any of `ApplicationDbContext` or `ApplicationUserManager` – XIVSolutions Jul 21 '15 at 23:13