0

I've been working with ASP.NET(WebForm) for a while, but new to ASP.NET MVC. From many articles I've read, in most cases the reason that the controllers are hard to test is because they are accessing the runtime components: HttpContext (including Request, Response ...). Accessing HttpContext in a controller seems bad.

However, I must access these components somewhere, reading input from Request, sending results back via Response, and using Session to hold a few state variables.

So where is the best place to access these runtime components if we don't access them in a controller?

3 Answers 3

1

when you call a model method in your controller, the Request and Response objects are carrying the same value or outputting to the same source. the "page" is what matters there for these objects.

And one more thing, the Request,Session and Response objects may not be directly referenced in your models so you can use System.Web.HttpContext.Current to get the objects. They will function the same as its called from the controller.

And Controllers meant to be as a bridge between views and models, and models should work even if there isn't any Response or Request value in these objects, so I would use these objects' values as usual parameters to model methods instead of referencing them inside the model. It's the right usage of the MVC concept.

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks! But I still didn't get the answer where is the best place to access those objects.
I think the answer is inside those sentences. I'll bold them for you.
0

If you really must access access these objects from your controller you could always just abstract them and inject a mock instance of them to isolate your testing to just the controller.

Comments

0

In MVC the HttpContext is actually HttpContextBase. It is completely fine to use these classes directly. If you need to later test your controllers you can mock these classes very easily.

http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx

I see nothing wrong with what you want to do.

Accessing HttpContext in a controller seems bad.

No it is not, it just requires you to think about how you will test your action. If you don't test, then you probably don't even have a problem. I recommend you test though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.