Get session cookie name

2019-06-25 11:45发布

问题:

Is it possible to get session cookie name in medium trust level? The code below works in full trust, but throws a security exception in medium trust level.

string sessionCookieName = ((SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState")).CookieName;

回答1:

You can use HTTP_COOKIE server variable from the Request object, to get the cookie string that was included with the request.

string cookieString = Request.ServerVariables["HTTP_COOKIE"]

If what you want is to obtain the session cookie name from the web.config, why don't you add a simple entry in the appSettings section containing the session cookie name?

    <appSettings>       
        <add key="SessionCookieName" value="__SessionCookieName"/>
    <appSetting>

    <sessionState cookieName="__SessionCookieName"  />        

Then you can read the web.config setting value by using the following code:

public static bool SessionCookieName
{
    get { return ConfigurationManager.AppSettings["SessionCookieName"]; }
}