Can the HttpContext be accessed within a ValidationAttribute in ASP.NET MVC?

旧街凉风 提交于 2019-12-19 06:19:08

问题


Can the HttpContext be accessed within a ValidationAttribute in ASP.NET MVC 3?

I need to test for something in my route data for a match in order to return true on my validator.

Thanks


回答1:


Yes, you can access the static HttpContext.Current property to get the current http context.

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.

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);

This abstraction will allow you to pass in mock http context base instances for easier testing.




回答2:


You can but why don't you use a RemoteValidationAttribute instead?



来源:https://stackoverflow.com/questions/6977637/can-the-httpcontext-be-accessed-within-a-validationattribute-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!