ServiceStack:访问服务中的 IRequest returns null

ServiceStack: Accessing the IRequest in the Service returns null

我正在使用 Servicestack。我的服务有一个基础 class,如下所示:

public abstract class ServiceHandlerBase : Service

然后是一些感兴趣的方法和属性。我已经有几种访问 IRequest 对象的方法,例如:

    protected AlfaOnline GetContactItem()
    {
        string deviceUUID = Request.Headers.Get(Constants.DEVICE_UUID); // <-- calling this method from constructor will give NullRef on Request here
        string authToken = Request.Headers.Get(Constants.AUTH_TOKEN);
        // do stuff
        return existingContactItem;
    }

在我的服务实现中运行良好,没有问题。

现在,我想直接从基础 class 使用完全相同的方法 ,在构造函数中调用它:

    public ServiceHandlerBase()
    {
        AlfaOnline ao = GetContactItem();
    }

但是如上所述,我在 Request 对象上得到了一个 NullReferenceException

请求对象何时可以访问和使用?因为它在服务实现中不是空的。

你不能在注入之前在构造函数中访问像 IRequest 这样的任何依赖项,它们只能在 Service class 初始化之后访问,就像 when您的服务方法被调用。

您可以使用 Custom Service Runner 在执行任何服务之前执行自定义逻辑,例如:

public class MyServiceRunner<T> : ServiceRunner<T> 
{
    public override void OnBeforeExecute(IRequest req, TRequest requestDto) {
      // Called just before any Action is executed
    }
}

并在您的 AppHost 中向 ServiceStack 注册它:

public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext ctx)
{           
    return new MyServiceRunner<TRequest>(this, ctx);
}

但是如果您只想 运行 服务 class 的一些逻辑,您现在可以在您的基础 class 中覆盖 OnBeforeExecute(),例如:

public abstract class ServiceHandlerBase : Service
{
    public override void OnBeforeExecute(object requestDto)
    {
        AlfaOnline ao = GetContactItem();
    }
}    

有关工作示例,请参阅 ServiceFilterTests.cs

如果您要实现 IService 而不是继承 Service 基础 class,则可以实现 IServiceBeforeFilter

新的服务过滤器从 v5.4.1 开始可用,现在 available on MyGet