6
我可以成功地將依賴項注入到我的ServiceStack服務中,但現在我需要將依賴項注入到請求過濾器中。但是,這看起來不是以同樣的方式工作。我可以在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始終爲空。
我想我必須在這裏缺少一些基本的東西。有沒有更好的方法來解決這個問題?
完美,謝謝。 – Simon