Skip to content

AspNetSession Layout Renderer

Rolf Kristensen edited this page Jun 11, 2023 · 8 revisions

ASP.NET Item Variable from Session Dictionary

Platforms Supported: All

Configuration Syntax

${aspnet-session:item=String:objectpath=String:format=String:ValueType=String|Int32}

Parameters

Rendering Options

  • item - Key for lookup in Session-dictionary (Required)

    Introduced with NLog.Web v5.1, and replaces the Variable-option

  • format - Format-specifier for converting the value as string (Optional)

    Introduced with NLog.Web v5.0

  • culture - Culture-specifier for converting the value as string (Optional)

    Introduced with NLog.Web v5.0

  • objectpath - Property path if the value is an object, also supports nested properties (Optional).

    Introduced with NLog.Web v5.2 and replaces EvaluateAsNestedProperties-option

  • ValueType - Only for ASP.NET Core. Type of the value. String (default) or Int32.

    Introduced in NLog.Web.AspNetCore 4.9.3. Please note: you won't get an error when retrieving a int (set with Session.SetInt32(..)) with valuetype string, but an incorrect value. We can't unfortunately recognize the type of the value inside the ASP.NET Core session.

See also Configure session state

Examples

Log the username in the session.

In the C# code:

Session["username"] = "JohnDoe";

Config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:item=username}" />
    </rules>
</nlog>

Will print "JohnDoe"

ObjectPath

In the C# code:

Session["user"] = new UserInfo { Name= "JohnDoe", Id = 100};

Config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:item=user:ObjectPath=Name}" />
    </rules>
</nlog>

Will print nested property-value "JohnDoe"

Clone this wiki locally