如何从 ServiceStack.Logging 获取当前用户

How to get current user from ServiceStack.Logging

我正在使用 ASP.NET MVC 和 servicestack.logging 我用的是log4net.

我需要获取已通过 servicestack-jwt 身份验证的当前用户。

在我的网络配置中使用以下代码,我只得到 windows 当前用户。

  <appender type="log4net.Appender.RollingFileAppender" name="User_Log">
  <file value="C:\logging\user_log\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="false" />

  <layout type="log4net.Layout.PatternLayout">
     <header type="log4net.Util.PatternString" value="[START LOG] %newline" />
     <footer type="log4net.Util.PatternString" value="[END LOG] %newline" />
    <conversionPattern value="[%property{log4net:HostName}] - [%username] - [%identity] - [%w] -%identity%newline%utcdate - %-5level - %message%newline" />
  </layout>

我也在Global.asax

中使用了下面的代码
       protected void Application_Start()
    {

        ServiceStack.Logging.LogManager.LogFactory = new ServiceStack.Logging.Log4Net.Log4NetFactory(true);

        //I can save test
        Logger.InfoFormat("test");

        string name = "";
        HttpContext context = HttpContext.Current;
        if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
        {
            name = context.User.Identity.Name;
        }
        //I can NOT save name
        _logger.InfoFormat(name);

    }

有什么帮助吗? 谢谢

ServiceStack, the Authenticated User is stored in the UserSession 中,可从 IRequest.GetSession() 访问。如果使用像 ASP.NET Framework 这样的 AppHost,它在 HttpContext.Current 单例中维护当前的 HttpContext,则可以通过以下方式访问它:

var req = HostContext.TryGetCurrentRequest();
var session = req.GetSession();
var userName = session.UserAuthName;