Saving Methods of session Value in C Program and Summarizing Methods of Converting session Value into String

  • 2021-09-16 07:51:16
  • OfStack

Three Methods of Saving Session in C # and Web. Config Settings

Saving session to sql server; Sql Server is required; Server, this method is the slowest to read and write to the database


<sessionState
mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20" />

Save session to windows process. To use this method, we need to open aspnet_state. exe service. Through this method, we can save session to other servers, which can realize session sharing among multiple servers


<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42626"
cookieless="false"
timeout="20" />

By default,. net saves session to the current process, which is the fastest way, but you cannot share session with multiple servers


<sessionState
mode= " InProc " 
cookieless= " false " 
timeout= " 20 " 
/>

Convert the value of Session to String
In practice, we often encounter changing the value of Session to String to judge whether it is empty or whether we have permission to access a page. If the conversion process here is not used properly, it will throw an exception, which will bring bad user experience to visitors. Here I write it as a note for reference.

1. When Session ["a"] = = null,

Session ["a"]. ToString () throws an exception;

(string) Session ["a"] is null;

Convert. ToString (Session ["a"]) is "".

2. When Session ["a"] = = "",

They all have a value of "".

Therefore, when determining whether Session ["a"] has a value, if ". ToString ()" is used, it must be written in the following format and order:


if (Session["a"] != null && Session["a"].ToString() != "")

Here, we should pay attention to the order of judgment: first judge whether it is null, and then judge whether it is empty. If Session ["a"] is null, then Session ["a"]! = If null is false, it will not be executed. ToString (), so no error will be reported; If Session ["a"] is not null, executing. ToString () will not report an error.

Similarly, the sentence if (Session ["a"] = = null Session ["a"]. ToString () = = "") is also valid.

The format of writing with. ToString () is relatively fixed. If you write with (string) instead, you will be more free:


if ((string)Session["a"] != null && (string)Session["a"] != "")

if (Session["a"] != null && (string)Session["a"] != "")

These two methods are feasible and have no relation to the order of null and empty.

The easiest way is to use Convert. ToString


if (Convert.ToString(Session["aaa"]) == "")

Whether Session ["a"] is null or empty, Convert. ToString (Session ["aaa"]) is empty.


Related articles: