locked
how to use session start in asp mvc in global.asax.cs RRS feed

  • Question

  • User-1634604574 posted

    i want to use seesion start like in php and make session variable and call it in any view as i wanted but without entity frame work code for log in and logout 

    can any one explainit by example?

    Friday, February 15, 2019 12:16 PM

Answers

  • User475983607 posted

    There are two many logical and design issues with your code to provider constructive feedback.  The main point is the authentication should happen on the server not on the client using JavaScript.  

    See the example code below.  Update the code to suite your needs.  However, I strongly recommend that you go through the Getting Started tutorials on this site to learn the basics.

    Models

        public class LoginViewModel
        {
            public string username { get; set; }
            public string password { get; set; }
        }
    
        public class LoginResult
        {
            public bool IsAuthenticated { get; set; }
            public string Message { get; set; }
        }

    Login Controller

        public class LoginController : Controller
        {
            [HttpGet]
            public ActionResult Login()
            {
                return View();
            }
    
            [HttpPost]
            public JsonResult Login(LoginViewModel Vm)
            {
                LoginResult result = Authenticate(Vm.username, Vm.password);
                if (result.IsAuthenticated)
                {
                    Session["Username"] = Vm.username;
                }
                return Json(result);
            }
    
            private LoginResult Authenticate(string username, string password)
            {
                LoginResult results = new LoginResult();
    
                string queryString = @"SELECT [UserId]
                                          ,[Username]
                                          ,[Password]
                                      FROM [dbo].[Users]
                                    WHERE [Username] = @username 
    	                                AND [Password] = @password";
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DemoDbConn"].ConnectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", password);
                    try
                    {
                        connection.Open();
                        var identity = command.ExecuteScalar();
    
                        results.IsAuthenticated = identity != null;
                        if (results.IsAuthenticated)
                        {
                            results.Message = $"Welcome {username}";
                        }
                        else
                        {
                            results.Message = $"Login failed!";
                        }
                    }
                    catch (Exception ex)
                    {
                        results.IsAuthenticated = false;
                        results.Message = ex.Message;
                    }
    
                }
                return results;
            }

    Login View

    @{
        ViewBag.Title = "Login";
    }
    
    <h2>Login</h2>
    
    <form action="Login">
        <div>
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Username"
                       name="username"
                       id="username"
                       type="text" 
                       value="email@email.com"/>
            </div>
    
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Password"
                       id="password"
                       name="password"
                       type="password" 
                       value="password"/>
            </div>
    
            <input type="submit" id="sign_in" class="btn btn-primary btn btn-outline-success" value="Sign In" />
        </div>
        <div id="message">
    
        </div>
    </form>
    
    @section scripts {
        <script>
            $("#sign_in").on("click", function (e) {
                e.preventDefault();
    
                var data = {
                    username: $("#username").val(),
                    password: $("#password").val(),
                };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Login", "Login")',
                    data: data,
                    dataType: "json"
                }).done(function (response) {
                    console.log(response);
                    if (response.IsAuthenticated) {
                         window.location.href = '@Url.Action("Main", "Main")';
                    }
                    else {
                        $('#message').text(response.Message);
                    }
                });   
            });;
        </script>
        }
    
    
    

    Main Controller

        public class MainController : Controller
        {
            public ActionResult Main()
            {
                return View();
            }
    @{
        ViewBag.Title = "Main";
    }
    
    <h2>Main</h2>
    
    <div>
        <input type="text" id="username" name="username" value="@Session["Username"]" />
    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 17, 2019 3:33 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    why not opening main view when log in is seccessful

    The code shown above invokes the Main.Main() action which returns the Main.  I tested the code once more to verify.  The code is functioning as expected.

    I made a slight change to the code which passes a message to /Main/Main if you are interested.

    Login View

    @{
        ViewBag.Title = "Login";
    }
    
    <h2>Login</h2>
    
    <form action="Login">
        <div>
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Username"
                       name="username"
                       id="username"
                       type="text" 
                       value="email@email.com"/>
            </div>
    
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Password"
                       id="password"
                       name="password"
                       type="password" 
                       value="password"/>
            </div>
    
            <input type="submit" id="sign_in" class="btn btn-primary btn btn-outline-success" value="Sign In" />
        </div>
        <div id="message">
    
        </div>
    </form>
    
    @section scripts {
        <script>
            $("#sign_in").on("click", function (e) {
                e.preventDefault();
    
                var data = {
                    username: $("#username").val(),
                    password: $("#password").val(),
                };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Login", "Login")',
                    data: data,
                    dataType: "json"
                }).done(function (response) {
                    console.log(response);
                    if (response.IsAuthenticated) {
                        window.location.href = '@Url.Action("Main", "Main")?message=' + response.Message;
                    }
                    else {
                        $('#message').text(response.Message);
                    }
                });   
            });;
        </script>
        }
    
    
    

    Main Action

        public class MainController : Controller
        {
            public ActionResult Main(string message)
            {
                ViewBag.Message = message ?? string.Empty;
                return View();
            }

    Main View

    @{
        ViewBag.Title = "Main";
    }
    
    <h2>Main</h2>
    
    <div>
        @ViewBag.Message
    </div>
    <div>
        <input type="text" id="username" name="username" value="@Session["Username"]" />
    </div>
    

    I feel it is important to understand the only difference between the code shown above and the many other code examples provided to you is the ADO.NET Authenticate() method.

    private LoginResult Authenticate(string username, string password)
    {
      ...
    }

    Secondly, we could have provided a timely solution if you had provided the source code.
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 17, 2019 9:38 PM

All replies

  • User753101303 posted

    Hi,

    You asked several time but once again browser session, authentication session and Entity Framework are all unrelated anyway. IMHO trying to implement your own login mechanism using the browser session is just a waste of time and more likely you'll end up with more vulnerabilities in your code (I saw recently someone who just stores the authenticated user name in a cookie). Also it will be harder to move your code forward if you later change your mind about that.

    IMO it would be better to start with :
    - what is the problem for not using EF at all ?
    - which authentication method are you using ? Windows ? Or user data are still stored in a db but you just don't want to use EF to access the database ?

    If having those constraints my first though would be to use ASP.NET Identity with my own SQL based provider.

    Friday, February 15, 2019 12:36 PM
  • User-1038772411 posted

    Paste This Code in global.asax.cs

    protected void Application_PostAuthorizeRequest()
    {
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    }

    Create Session Variable and use it as you want like in view page or controller.

    public static string id
    {
      get => convert.string(HttpContext.Current.Session["id"]);
      set => HttpContext.Current.Session["id"] = value;
    }

    Use "id" Variable publicly as a sessoin variable like :

    if(Session["id"] != null) { ...Code...}

    Friday, February 15, 2019 12:44 PM
  • User753101303 posted

    I believe the OP wants to implement his own authencation method based on using session variables. Not sure though which piece is missing and if the problem is really with session variables or the SQL code or whatever...

    @zhyanadil, if you insist for doing things this way could you give some feedback on the very first problem you have when trying to do so. I believe you had several answers but it's easier to help if knowing the exact problem which can avoid to spend time on sample code that anyway could still not solve your real problem.

    Friday, February 15, 2019 12:51 PM
  • User-1634604574 posted

    from where write this code?

    if(Session["id"] != null) { ...Code...}

    can you give me example more detail about view and controller ?
    Friday, February 15, 2019 1:54 PM
  • User753101303 posted

    When using ASP.NET out of the box features you are just adding 

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // maybe something else...
        filters.Add(new AuthorizeAttribute());
    }

    and so by default all controllers are requiring the user to be authenticated.  Then on those that needs to be publicly available you are using AllowAnonymous. See for example :
    https://www.davidhayden.me/blog/asp.net-mvc-4-allowanonymous-attribute-and-authorize-attribute

    Now if you want to check a session variable instead a way to do so would be to create your own AuthorizeAttribute :
    https://dougrathbone.com/blog/2011/07/24/writing-your-own-custom-aspnet-mvc-authorize-attributes

    Now if you want to go with global.asax you could try to do that in protected void Application_AuthenticateRequest(object sender, EventArgs e) but you likely won't find much support for that as this is rarely done unless maybe for some very specific needs.

    Friday, February 15, 2019 2:41 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    i want to use seesion start like in php and make session variable and call it in any view

    Session_Start() in PHP is an API to control how Session is implemented; cookie based, DB, named session etc.  ASP.NET does not work the same way (ASP.NET Core is similar).  In ASP.NET Session is configured in the web.config where the default is "InProc".  InProc uses a cookie.  I have provided links to ASP.NET Session references in several of your previous threads. 

    The global.asax in ASP.NET has a Session_Start event.  The Session_Start event fires when a user first accesses the site.  The Application_PostAcquireRequestState event runs once state has been acquired.  You can take advantage of these events to handle your Session logic.  Please see the Application Life Cycle.

    The following example extended sample code I provided in your other threads.

    Add these two method to the Global.asax

            protected void Session_Start()
            {
                Session["Session_Start"] = $"Session_Start {DateTime.Now}";            
            }
           
            protected void Application_PostAcquireRequestState()
            {
                Session["Application_PostAcquireRequestState"] = $"Application_PostAcquireRequestState {DateTime.Now}";         
            }

    Index View

    @{
        ViewBag.Title = "Index";
    }
    
    
    
    <div id="content">
        <h2>Index</h2>
        @using (Html.BeginForm("Main", "Test"))
        {
            <div>
                <input id="username" name="username" />
            </div>
            <div>
                <input id="Submit1" type="submit" value="submit" />
            </div>
    
            <div>
                @if (Session["username"] == null)
                {
                    <span>No Session Here</span>
                }
                else
                {
                    <span>Welcome @Session["username"]</span>
                }
            </div>
            <div>
                <ul>
                    <li> @Session["Session_Start"]</li>
                    <li> @Session["Application_PostAcquireRequestState"]</li>
                </ul>
            </div>
    
    
        }
    </div>

    Main View

    @{
        ViewBag.Title = "Main";
    }
    
    <h2>Main</h2>
    
    <div>
        Welcome @Session["username"] <br />
        Click the link below to  verify Session will persist across requests.
    </div>
    <div>
        @Html.ActionLink("Verify Session Works", "Index")
    </div>
    <div>
        <ul>
            <li> @Session["Session_Start"]</li>
            <li> @Session["Application_PostAcquireRequestState"]</li>
        </ul>
    </div>

    Run the app and should get the idea.

    zhyanadil.it@gmail.com

    from where write this code?

    if(Session["id"] != null) { ...Code...}
    
    can you give me example more detail about view and controller ?

    You would write this code where ever you want to check if Session["id"] is null then, I assume, set session.  

    Friday, February 15, 2019 3:22 PM
  • User-1634604574 posted

    how about this code i don't understand it used for what?

    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    and this code i don't know write this from where and used for what?
    public static string id
    {
      get => convert.string(HttpContext.Current.Session["id"]);
      set => HttpContext.Current.Session["id"] = value;
    }

     

    Friday, February 15, 2019 8:39 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    how about this code i don't understand it used for what?

    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    and this code i don't know write this from where and used for what?
    public static string id
    {
      get => convert.string(HttpContext.Current.Session["id"]);
      set => HttpContext.Current.Session["id"] = value;
    }

     

    Perhaps try reading the docs as it helps.

    https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcontext.setsessionstatebehavior?view=netframework-4.7.2

    The static property is just that, static access to the "Id" field. 

    Friday, February 15, 2019 9:35 PM
  • User-1634604574 posted

    till now my problem is not solved

    i want when a user logged in create a session variable and set textbox username value to it and can call that session variable from any other view as i wanted

    Friday, February 15, 2019 9:40 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    till now my problem is not solved

    i want when a user logged in create a session variable and set textbox username value to it and can call that session variable from any other view as i wanted

    The example above and previous responses meet this requirement.   The only caveat is you cannot close the browser and the site cannot be behind a load balancer as Session is stored in server memory.

    Friday, February 15, 2019 10:07 PM
  • User-1634604574 posted

    i have this method in controller

    controler name:Login
    public JsonResult test_login(String username, String password)
    {
    SqlCommand com = new SqlCommand("select Username,Set_new_password from Users where Username='" + username + "' and Set_new_password='" + password + "'", con);
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataSet ds = new DataSet();

    da.Fill(ds);
    List<auto_complete_2> listreg = new List<auto_complete_2>();
    foreach (DataRow dr in ds.Tables[0].Rows)
    {
    listreg.Add(new auto_complete_2
    {
    username = dr["Username"].ToString(),
    password = dr["Set_new_password"].ToString(),


    });
    }
    return Json(listreg, JsonRequestBehavior.AllowGet);
    }

    --------------------------------------------------------------------------
    here is my view

    <div class="form-group col-md-offset-2" style="margin-left:5px">
    <input class="form-control" placeholder="Username" id="username" type="text" style="background-color:white;width: 310px; ">
    </div>

    <div class="form-group col-md-offset-2" style="margin-left:5px">
    <input class="form-control" placeholder="Password" id="password" type="password" style="background-color:white;width: 310px;">
    </div>

    <input type="submit" onMouseOver="this.style.color='white'" id="sign_in" class="btn btn-primary btn btn-outline-success" value="Sign In" style="margin-left:5px;width:310px;font-size:10pt" />


    my script by clicking on sign in button will cheking user and password

    $("#sign_in").on("click", function () {

    $.ajax({
    type: 'POST',
    url: '/Login/test_login',
    data: {
    username: $("#username").val(),
    password: $("#password").val(),
    },
    success: function (response) {
    data = $.map(response, function (item, a) {

    $("#user_compare").val(item.username);
    $("#password_compare").val(item.password);


    });
    },
    dataType: "json"
    }).done(function () {


    if ($("#password_compare").val()!="" && $("#user_compare").val()!="" && $("#username").val() == $("#user_compare").val() && $("#password").val() == $("#password_compare").val()) {

    $("#im_blue").hide()
    $("#im_green").show()
    $("#im_red").hide()
    $("#p_sign_in").text("Success")

    window.location.href = '@Url.Action("Main", "Main")' + "?username=" + $("#username").val();

    }

    if ($("#user_compare").val() == "" && $("#password_compare").val() == "")
    {
    $("#im_blue").hide()
    $("#im_green").hide()
    $("#im_red").show()
    $("#p_sign_in").text("Invalid Username or Password")
    $("#p_success").hide()
    }


    if ( $("#username").val() != $("#user_compare").val() && $("#password").val() != $("#password_compare").val()) {

    $("#im_blue").hide()
    $("#im_green").hide()
    $("#im_red").show()
    $("#p_sign_in").text("Invalid Username or Password")
    $("#p_success").hide()
    }

    if ($("#username").val() == "" && $("#password").val() == "") {


    $("#im_blue").hide()
    $("#im_green").hide()
    $("#im_red").show()
    $("#p_sign_in").text("please enter username and password")
    $("#p_success").hide()
    }

    })


    })

    if username and password is correct go to the home page now i want to put that username in textbox username into the variable and call it in all views which is each
    view in different controller here is my problem i cannot call that username value which is textbox username i cannot call it in all views

    Sunday, February 17, 2019 4:37 AM
  • User475983607 posted

    There are two many logical and design issues with your code to provider constructive feedback.  The main point is the authentication should happen on the server not on the client using JavaScript.  

    See the example code below.  Update the code to suite your needs.  However, I strongly recommend that you go through the Getting Started tutorials on this site to learn the basics.

    Models

        public class LoginViewModel
        {
            public string username { get; set; }
            public string password { get; set; }
        }
    
        public class LoginResult
        {
            public bool IsAuthenticated { get; set; }
            public string Message { get; set; }
        }

    Login Controller

        public class LoginController : Controller
        {
            [HttpGet]
            public ActionResult Login()
            {
                return View();
            }
    
            [HttpPost]
            public JsonResult Login(LoginViewModel Vm)
            {
                LoginResult result = Authenticate(Vm.username, Vm.password);
                if (result.IsAuthenticated)
                {
                    Session["Username"] = Vm.username;
                }
                return Json(result);
            }
    
            private LoginResult Authenticate(string username, string password)
            {
                LoginResult results = new LoginResult();
    
                string queryString = @"SELECT [UserId]
                                          ,[Username]
                                          ,[Password]
                                      FROM [dbo].[Users]
                                    WHERE [Username] = @username 
    	                                AND [Password] = @password";
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DemoDbConn"].ConnectionString))
                {
                    SqlCommand command = new SqlCommand(queryString, connection);
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", password);
                    try
                    {
                        connection.Open();
                        var identity = command.ExecuteScalar();
    
                        results.IsAuthenticated = identity != null;
                        if (results.IsAuthenticated)
                        {
                            results.Message = $"Welcome {username}";
                        }
                        else
                        {
                            results.Message = $"Login failed!";
                        }
                    }
                    catch (Exception ex)
                    {
                        results.IsAuthenticated = false;
                        results.Message = ex.Message;
                    }
    
                }
                return results;
            }

    Login View

    @{
        ViewBag.Title = "Login";
    }
    
    <h2>Login</h2>
    
    <form action="Login">
        <div>
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Username"
                       name="username"
                       id="username"
                       type="text" 
                       value="email@email.com"/>
            </div>
    
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Password"
                       id="password"
                       name="password"
                       type="password" 
                       value="password"/>
            </div>
    
            <input type="submit" id="sign_in" class="btn btn-primary btn btn-outline-success" value="Sign In" />
        </div>
        <div id="message">
    
        </div>
    </form>
    
    @section scripts {
        <script>
            $("#sign_in").on("click", function (e) {
                e.preventDefault();
    
                var data = {
                    username: $("#username").val(),
                    password: $("#password").val(),
                };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Login", "Login")',
                    data: data,
                    dataType: "json"
                }).done(function (response) {
                    console.log(response);
                    if (response.IsAuthenticated) {
                         window.location.href = '@Url.Action("Main", "Main")';
                    }
                    else {
                        $('#message').text(response.Message);
                    }
                });   
            });;
        </script>
        }
    
    
    

    Main Controller

        public class MainController : Controller
        {
            public ActionResult Main()
            {
                return View();
            }
    @{
        ViewBag.Title = "Main";
    }
    
    <h2>Main</h2>
    
    <div>
        <input type="text" id="username" name="username" value="@Session["Username"]" />
    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 17, 2019 3:33 PM
  • User-1634604574 posted

    why not opening main view when log in is seccessful

    Sunday, February 17, 2019 7:50 PM
  • User475983607 posted

    zhyanadil.it@gmail.com

    why not opening main view when log in is seccessful

    The code shown above invokes the Main.Main() action which returns the Main.  I tested the code once more to verify.  The code is functioning as expected.

    I made a slight change to the code which passes a message to /Main/Main if you are interested.

    Login View

    @{
        ViewBag.Title = "Login";
    }
    
    <h2>Login</h2>
    
    <form action="Login">
        <div>
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Username"
                       name="username"
                       id="username"
                       type="text" 
                       value="email@email.com"/>
            </div>
    
            <div class="form-group col-md-offset-2" style="margin-left:5px">
                <input class="form-control"
                       placeholder="Password"
                       id="password"
                       name="password"
                       type="password" 
                       value="password"/>
            </div>
    
            <input type="submit" id="sign_in" class="btn btn-primary btn btn-outline-success" value="Sign In" />
        </div>
        <div id="message">
    
        </div>
    </form>
    
    @section scripts {
        <script>
            $("#sign_in").on("click", function (e) {
                e.preventDefault();
    
                var data = {
                    username: $("#username").val(),
                    password: $("#password").val(),
                };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("Login", "Login")',
                    data: data,
                    dataType: "json"
                }).done(function (response) {
                    console.log(response);
                    if (response.IsAuthenticated) {
                        window.location.href = '@Url.Action("Main", "Main")?message=' + response.Message;
                    }
                    else {
                        $('#message').text(response.Message);
                    }
                });   
            });;
        </script>
        }
    
    
    

    Main Action

        public class MainController : Controller
        {
            public ActionResult Main(string message)
            {
                ViewBag.Message = message ?? string.Empty;
                return View();
            }

    Main View

    @{
        ViewBag.Title = "Main";
    }
    
    <h2>Main</h2>
    
    <div>
        @ViewBag.Message
    </div>
    <div>
        <input type="text" id="username" name="username" value="@Session["Username"]" />
    </div>
    

    I feel it is important to understand the only difference between the code shown above and the many other code examples provided to you is the ADO.NET Authenticate() method.

    private LoginResult Authenticate(string username, string password)
    {
      ...
    }

    Secondly, we could have provided a timely solution if you had provided the source code.
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 17, 2019 9:38 PM