如何根据请求在 Windsor 中获取 HttpContext

How to get HttpContext within Windsor per request

我正在使用温莎城堡实施审计管理器。但是,我不确定如何获取每个请求当前正在执行的 HttpContext。我需要它来记录请求中的某些信息,例如 I.P。地址。如果可能的话,您能否也告诉我是否有安全简单的方法将 return 值转换为 JsonResult 对象(如果是那种类型)?

public class ControllersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Classes.FromThisAssembly()
            .BasedOn<IController>()
            // a new instance should be provided by Windsor every time it is needed
            .LifestyleTransient()
            .Configure(c => c.Interceptors(new InterceptorReference(typeof(ControllerInterceptor)))));
    }

    public class ControllerInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            try
            {
                string controller = invocation.TargetType.FullName;
                string method = invocation.Method.Name;
                List<string> parameters = new List<string>();

                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    var param = invocation.Arguments[i];
                    parameters.Add(param.ToString());
                }

                invocation.Proceed();

                string result = JsonConvert.SerializeObject(invocation.ReturnValue ?? new object());

                var auditItem = new AuditItem
                {
                    ActionRequested = method,
                    Controller = controller,
                    Denied = false,
                };

            }
            catch (Exception ex)
            {
                _log.Error("ControllerInterceptor.Intercept:: " + ex.Message, ex);
            }
        }
    }

您可以向 Castle Windsor 注册一个 HttpContextBase 并使用工厂方法解析它。使用 PerWebRequest 生活方式来确保它适用于每个请求。

container.Register(
    Component.For<HttpContextBase>()
             .UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current))
             .LifestylePerWebRequest());