简体   繁体   中英

How to access HttpContext from controller in ASP.NET mvc

In asp.net how do i get the current httpcontext for the page that i am on?

i have tried giving the relevant controller the httpcontext as an argument, but this does not work. I have found plenty of people describing how to specify the object, but i simply cannot find any info on how the httpcontext should be added to the controller (like, in a argument or so)

this does not work

    public class MovieController : Controller
    {
            public ActionResult Random(HttpContext mycontext)
        {

            RandomMovieViewmodel rmvm = new RandomMovieViewmodel();


            return View(rmvm);
        }

How do i acces the context? should I maybe make a attribute?

Controller definition is really important here.

For example, in.Net Core 2.2 with a Controller derived from ControllerBase, HttpContext exposed as a property.

I'm not sure about your environment or your class definition, but it always similar in Asp.Net MVC. Just make sure that, you defined your Controller class correctly.

UPDATE

When you derived from Controller class, HttpContext exposed as property. You can directly use it.

public class TestController : Controller
{
    public ActionResult Index()
    {
        var context = HttpContext;

        return View();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM