2

I want to store login information of a user globaly. If user is logged in already , then if another user want to login from another PC somewhere than application must warn him that another user is also logged in with this name.

I dont' want to use DataBase. I think HttpApplication is a solution. But I can't understand its flow.

What I know is , I have to assign values to it in Global.asax.cs file :

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
             Application["Username"] = "Test";
        }
   }

Now i want to access it in a controller , in Login Function where I would check if Application has some data or not.

If it is null than there is no user logged in. But I don't understand how to access HTTPApplication object and how to assign the username to it in the Application_Start().

Hammad Shahid
  • 2,216
  • 5
  • 32
  • 60
  • Keep in mind that once the `application pool` is recycled, you lose all your `Application` data. – haim770 Sep 03 '13 at 10:27

2 Answers2

3

In a controller you can access the application object. Ie.

public ActionResult Index()
        {
            string value = HttpContext.Application["a"] as string;
            if (value == null){
                value = DateTime.Now.ToLongTimeString();
                HttpContext.Application["a"] = value;
            }

            return Content(value);                
        }
Stefano Altieri
  • 4,550
  • 1
  • 24
  • 41
  • Actually I want to store whole object of the user , it contains some additional information. – Hammad Shahid Sep 03 '13 at 10:27
  • I did this: `string obj = HttpContext.Application["a"]; if(obj == null ) { HttpContext.Application["a"] = "b"; }` And on every new request , it is entering in `if` condition i.e. obj is null – Hammad Shahid Sep 03 '13 at 10:29
  • ??? This makes no sense... have you got a load balancer or more then one web server? If so see http://stackoverflow.com/questions/7449709/application-variable-across-load-balanced-servers-asp-net – Stefano Altieri Sep 03 '13 at 11:00
  • There are no load balancers , and web server is also one – Hammad Shahid Sep 03 '13 at 11:13
0

Try this,

string value = HttpContext.Current.Application["a"] as string;
Jatin patil
  • 4,252
  • 1
  • 18
  • 27