Background:
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. This works for that application but when we have a class library referenced in that application and we need Session Variables
in that library, I have to pass it to each method as I am not using dependency injection.
Problem:
I have a controller which does Facebook authentication as below:
public class FacebookController : Controller
{
private FacebookGateway FacebookGateway = new FacebookGateway();
// GET: /Facebook/
public ActionResult Index()
{
string code = Request.QueryString["code"];
TokenResponse tokenResponse = FacebookGateway.GetTokenResponse(code);
Session["AccessToken"] = tokenResponse.Access_token;
return View();
}
public ActionResult Friends()
{
string accessToken = Session["AccessToken"].ToString();
WebRequest request = WebRequest.Create(instanceUrl + @"profileUrl-Here");
request.Method = "GET";
request.Headers.Add("Some Header " + accessToken);
WebResponse response = request.GetResponse();
string str = String.Empty;
if (response == null)
{
}
else
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
str = sr.ReadToEnd().Trim();
}
//Convert str to Model
return View(model);
}
Here, in almost each method I need access token for data access from Facebook Graph API, but, I have to take it from session each time as follows
var accessToken = Session["AccessToken"].ToString();
How can I make it available to all the methods in the controllers?
Is there any way to share the session between MVC and class library without passing HttpContext.Session
in each method call for class library?
Note: I have seen this answer, but it was not quite clear how can it be available in class library too.