GONeale
GONeale

Reputation: 26484

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

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

Upvotes: 9

Views: 3625

Answers (2)

Lee Smith
Lee Smith

Reputation: 6777

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

Upvotes: 0

nikmd23
nikmd23

Reputation: 9113

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.

Upvotes: 7

Related Questions