1

I'm trying to access a method of my MVC HomeController from another controller to redirect the user to the homepage if he is not authenticated. The problem is that the Session in my HomeController is not setted if I instantiate it on my own, but I have to access a variable stored in the session from my HomeController. I tried to solve the problem this way:

HomeController currentHomeController = new HomeController();
currentHomeController.Session = this.Session;
return currentHomeController.Index();

But the Session variable has no setter so this does not work. Is there a different way to do this?

My Solution

This works:

 return RedirectToAction("Index", "Home");

Thanks for your answers!

1
  • You can't create your own instance of the Controller like this, that's what's causing all your problems. The ASP.NET framework creates the instances of controllers. If you want to re-use action methods, the normal way is to redirect the client to the action method you want, like this: stackoverflow.com/a/27057561/7724 Commented Nov 21, 2014 at 9:08

3 Answers 3

5

You can access Session through Http.Context.Current

In your other class:

var myVar = HttpContext.Current.Session["MyVar"]

If you need to redirect to another action just RedirectToAction in your acction

return RedirectToAction("MyAction", "MyController")
Sign up to request clarification or add additional context in comments.

3 Comments

Found this solution already in the web, but HttpContext has no property "Current" in my solution. I'm using ASP.Net MVC 5.
@PhilippEger do you perform this in the web project or in another library?
The old ASP.NET Web Forms "Current" static way of accessing the HTTP Context isn't normally used in ASP.NET MVC. All the different context items are injected into the Controller instance by the Action Invoker.
4

For redirect to another controller action you don create instance from it ..you use from

TempData["Key"]="lol";
or
Session["key"]="lol";
return RedirectToAction("ActionName", "ControllerName");

For session you can store yor data in TemData["key"] Or Session["key"] and get it your another action like

var data=TempData["Key"]; 
Or
var data =Session["key"];

Comments

0

A controller's Session object is pre-populated by the framework. They all point to the same Session object, so you can just use it without setting it

In Controller1

this.Session["MyText"] = "hello from Controller1";

and then in Controller2

model.MyText = this.Session["MyText"] as string;

This is a typical way of passing data between requests

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.