locked
Adding Session variables in a Controller page RRS feed

  • Question

  • User-1767698477 posted

    My controller is in vb.net.  I need to be able to access session variables and enable session state. Right now if I type httpcontext.current.session it is underlined in red.   I have done some reading on this, but I'm unclear of the exact steps. I believe the global.asax page has to be modified. Do I also need to create some class files ? If so, where do they go?

    I read an article and here is some code. Can someone please clarify how this is implemented?

    Public Class AspApplication
    Inherits System.Web.HttpApplication
    
    Protected Sub Application_PostAuthorizeRequest()
    If IsWebApiRequest() Then
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required)
    End If
    End Sub
    
    Private Function IsWebApiRequest() As Boolean
    Return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative)
    End Function
    End Class
    
    
    Public Shared Sub Register(ByVal routes As RouteCollection)
    routes.MapHttpRoute(name:="DefaultApi", routeTemplate:=WebApiConfig.UrlPrefix & "/{controller}/{id}", defaults:=New With {Key
    .id = RouteParameter.[Optional]
    })
    End Sub
    
    
    And then call the following in Application_Start:
    
    WebApiConfig.Register(RouteTable.Routes);
    
    
    

    Sunday, June 7, 2020 10:58 PM

Answers

  • User-1767698477 posted

    I have it working. Thanks for the suggestion.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 4, 2020 4:35 AM

All replies

  • User1686398519 posted

    Hi,  sking

    There are two ways to add a session.

    HttpContext.Session.Add("test1", "1")
    Dim test1 = HttpContext.Session("test1")

    Or

    Session("test2") = "2"
    Dim test2 = Session("test2")

    Here is the result.

     
    Best Regards,

    YihuiSun

    Monday, June 8, 2020 10:50 AM
  • User-474980206 posted

    if you are just starting with MVC, you should use C# or F#, as VB will not be supported with future versions. You also might want to look at asp.net core rather than starting with an end of life product.

    Monday, June 8, 2020 3:06 PM
  • User-1767698477 posted

    I have it working. Thanks for the suggestion.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 4, 2020 4:35 AM