问题描述
是否可以在ASP.NET MVC 3的 ValidationAttribute
中访问 HttpContext
?
Can the HttpContext
be accessed within a ValidationAttribute
in ASP.NET MVC 3?
我需要测试路线数据中是否有匹配项,以便在验证器上返回true。
I need to test for something in my route data for a match in order to return true on my validator.
谢谢
推荐答案
是的,您可以访问静态HttpContext.Current属性以获取当前的http上下文。
Yes, you can access the static HttpContext.Current property to get the current http context.
此属性可能会返回null,具体取决于您在哪个线程上运行验证,或在非http请求(例如单元测试)中运行验证。
This property may return null depending on what thread you are running your validation on, or in a non http request such as in a unit test.
您将很可能希望抽象出您对.Current的调用,以创建更多可测试的代码。为此,请让您的抽象成员返回HttpContextBase,如下所示:
You will most likely want to abstract away the call you make to .Current in order to create more testable code. To do this, have your abstracted member return an HttpContextBase, like this:
return new HttpContextWrapper(HttpContext.Current);
此抽象将使您可以传递模拟http上下文基础实例,以便于测试。
This abstraction will allow you to pass in mock http context base instances for easier testing.
这篇关于可以在ASP.NET MVC的ValidationAttribute中访问HttpContext吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!