I am populating an instance of a class that represents the session variable and exists in a class library. I need to populate one property that requires me to get access t开发者_如何学编程o the Request
object. I understand that I can use the System.Web.HttpContext.Current.Request
to get the request object?
Is this a good practice. Something tells me that I should be doing this in the controller (or the base controller) that has the System.Web
namespace.
Its not a bad practice - the object is available - if you design dictates to access it there - then by all means do it. One option is to pass in an instance of the request to the class's constructor if it makes you feel cleaner : )
According to Teemu Keiski on the ASP.NET forums:
You could use
System.Web.HttpContext.Current
but that's bad practise since it makes your class library totally unusable outside web applications (and if you access Sessions via that, it also gets unusable for web services in most scenarios).Anything you pass by getting straight HttpContext could be passed as parameters into the class that needs it. And if you need to access Response object directly, you could pass
Response.OutputStream
into the class (which would take it as general Stream object)
Source: http://forums.asp.net/post/1311405.aspx
Fundamentally there's nothing wrong with this as long as you take a dependency on System.Web.Abstractions
and pass into your class a reference to HttpRequestBase
. The classes in this assembly are not sealed and all members are virtual which means your class will still be testable.
More info in the answers to the following SO question
精彩评论