how to decouple controller from Http context session
I need to store some data in session inside my action however I'm concerned about coupling my controller to the http context session, I have thought about creating a service, but is it really开发者_如何学C worth it?
No, it isn't worth it. It is the controller that has access to the Http Context including the session. Not to mention that you already are working with an abstraction of the session: HttpSessionStateBase which can be easily mocked in a unit test.
There might be situations where you could have your business methods take ICollection as input parameter which is an interface implemented by HttpSessionStateBase
and then have the controller pass the Session
object to them.
Especially for ApiControllers
, build yourself a DelegatingHandler
and push all of your goodies onto request.Properties
. You can then retrieve them from your request whether you are testing or running live. The benefit is that you then have zero dependency on Session in your Controller.
MessageHandler
public class ContextHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
// get the goodies to add onto the request
var goodies = /* call to goodieGoodieYumYum */
// add our goodies onto the request
request.Properties.Add(Constants.RequestKey_Goodies, goodies);
// pass along to the next handler
return base.SendAsync(request, cancellationToken);
}
}
Controller Action
var goodies = (List<Goodie>)Request.Properties[Constants.RequestKey_Goodies];
精彩评论