我们的模型有自定义序列化程序,可根据请求路径保护敏感数据。 (例如,如果请求不以“/ admin”开头)。
到目前为止,我们已经尝试使用ReuseScope.None或ReuseScope.Request在RequestFilter上使用Funq容器注册IHttpRequest,并且在序列化器上,我们从容器中获取IHttpRequest。
我们发现如果有多个请求待处理,容器将返回最后一次注册的IHttpRequest,它不一定是正确的请求对象。
我知道我们可以尝试在应用过滤器属性的模型上实现对敏感数据的这种保护,但这非常麻烦,因为我们的模型对象通常嵌入在其他对象或集合中。
如果没有能够从序列化程序中获取正确的HttpRequest对象的问题,让序列化程序执行它是迄今为止最好的解决方案。
那么,这样做的正确方法是什么?或者这是一种不好的做法?
这里有几个代码示例:
所以这是一个私有方法,我的序列化程序用它来定义它们是否在“admin”路由中被序列化:
private bool IsAdminRoute() {
var path = container.Resolve<IHttpRequest> ().PathInfo;
var res = path.StartsWith ("/admin");
return res;
}
以下是它的用法:
public Question QuestionSerializer(Question question)
{
if (!IsAdminRoute())
{
// do stuff like nullyfying certain properties
}
return question;
}
在我的AppHost初始化中,我有:
void ConfigureSerializers(Funq.Container container)
{
Serializers = new CustomSerializers ();
// ...
JsConfig<Question>.OnSerializingFn = Serializers.QuestionSerializer;
// ...
}
public void HttpRequestFilter(IHttpRequest httpReq, IHttpResponse httpRes, object dto) {
Container.Register <IHttpRequest>(c => httpReq).ReusedWithin (Funq.ReuseScope.Request);
}
注意:我正在使用ServiceStack v3。
答案 0 :(得分:0)
我设法通过这种方式注册IHttpRequest来使其工作:
container.Register(c => HttpContext.Current.ToRequestContext ().Get<IHttpRequest>()).ReusedWithin(Funq.ReuseScope.None);
现在,当我尝试解决它时,我总是得到IHttpRequest对象。
此外,在我的应用程序中进行了更多的测试之后,我能够检测到,如果并发性足够高,依赖于使用ReuseScope.Request注册的所有内容都会混淆。
解决方案非常简单,我现在依赖于HttpContext.Current.Items集合来存储这些特定于请求的依赖项,并将它们注册到请求过滤器上,如下所示:
HttpContext.Current.Items ["Token"] = token;
container.Register<Token> (c => (Token)HttpContext.Current.Items["Token"]).ReusedWithin(Funq.ReuseScope.None);
现在它按照预期的方式工作。