warheat1990 warheat1990 - 27 days ago 5x
C# Question

Is it possible to load object and reuse said object in separate HTTP call?

So I have a WEB API, for example I have this method :

public JSONResult GetUserInfo(string username)
Reddit reddit = new Reddit("bot12345", "12345"); //load reddit and login

var user = User.Get(username);

//rest of the code here

You can see that I have this line
Reddit reddit = new Reddit("bot12345", "12345")
, this line took almost 2 seconds because it needs to login through Reddit API. So everytime someone call
method, my code will take more than 2 seconds to return the results because it needs to call Reddit.

I was wondering if it's possible to load Reddit object so inside my GetUserInfo method, I only need to call
. But I remember that HTTP is stateless, so is that possible?

Apologize for bad english.


HTTP is stateless, but ASP.NET has a Session object that is isolated to one user session and can store data that persists across requests. So at a minimum you could do something like:

Reddit reddit = Session["reddit"] as Reddit;
if(reddit == null)
    reddit = new Reddit("bot12345", "12345"); //load reddit and login
    Session["reddit"] = reddit;

If the same Reddit object can be used for all user sessions, then you can use the Application class instead of using Session.