Search code examples
c#asp.netweb-servicesasmx

How to exchange session variables between webmethods in asp.net webservices


I have the following code to store session variable in one webmethod and retrieve it in other webmethod but the value displays null when i try to retrieve it.

[WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public bool SubmitList1(string businessname )
    {

        Session["Company_Name"] = businessname;  

        SqlConnection con = new SqlConnection();
             .......
           .........
                .........

  }

This will be my second webmethod where i am trying to retrieve the session variable

[WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public bool addresslisting()
    {

        string companyname = (string)Session["Company_Name"];// this particular value is displaying null
       ......
           ........

}

Solution

  • This is a double-post to how to exchange session or cookie variables between two webmethods in asp.net webservices , so here it comes again:

    Disclaimer: I think that a web service that relies on Session state is just plain WRONG since a web service should be stateless. However:

    At http://msdn.microsoft.com/en-us/library/aa480509.aspx you can read about how to use ASP.NET Session in a web service:

    1. Make sure that /configuration/system.web/sessionState in web.config is configured properly to enable session state
    2. Make sure that uses the web service has a cookie container where the ASP.NET session cookie can be stored. If the client is from a web browser (e.g. ajax call) this usually works out of the box, but if you are building a standalone client, you have to do some more work, see the link above.

    All in all: a bad design decision gives you more work than necessary (sorry for rubbing it in).

    I think you should redesign you web service so that you either always send username and password in all methods or add a login method that gives the client a token that is sent with each web service request.