我可以成功地将依赖项注入到我的 ServiceStack 服务中,但现在我需要将依赖项注入到请求过滤器中。然而,这似乎并没有以同样的方式工作。
这是我的过滤器(它只是检查源 IP 是否在批准的列表中;我要注入的就是这个列表):
public class CheckIPFilter : RequestFilterAttribute
{
private readonly IList<string> _IPAddresses = new List<string>();
public CheckIPFilter() { }
public CheckIPFilter(IList<string> IPAddresses)
{
_IPAddresses = IPAddresses;
}
public override void Execute(ServiceStack.ServiceHost.IHttpRequest req, ServiceStack.ServiceHost.IHttpResponse res, object requestDto)
{
if (!_IPAddresses.Contains(req.UserHostAddress))
{
var errResponse = DtoUtils.CreateErrorResponse("401", "Unauthorised", null);
var responseDto = DtoUtils.CreateResponseDto(requestDto, new ResponseStatus("401", "Unauthorised"));
var contentType = req.ResponseContentType;
var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(contentType);
res.ContentType = contentType;
var serializationContext = new HttpRequestContext(req, res, responseDto);
serializer(serializationContext, responseDto, res);
res.EndRequest(); //stops further execution of this request
return;
}
}
}
这就是我的 global.asax 中的内容:
var IPAddresses = new List<string>()
{ "99.99.99.99", "99.99.99.99", "99.99.99.99", "99.99.99.99" };
container.Register<IList<string>>(IPAddresses);
_IPAddresses 始终为空。
我想我一定在这里遗漏了一些基本的东西。有没有更好的方法来解决这个问题?