Using Sessao on a MVC controller returns error

Asked

Viewed 201 times

2

I am trying to use session in an MVC application, I believe you are right but it is returning the error:

Undefined object reference for an object instance

when it tries to pass the value in the session and the value is not null.

I think this is not the proper way to use MVC session, someone knows what I’m doing wrong?

[HttpPost]
        [Route("FiltroSiltDet")]
        public HttpResponseMessage FiltroSiltDet(string DT_INCLUSAO)
        {
            try
            {
                HttpSessionState Session = HttpContext.Current.Session;
                Session["DT_INCLUSAO"] = "test";
                Session["DT_INCLUSAO"] = DT_INCLUSAO;
                List<AcompanhamentoSiltDetDTO> retorno = new List<AcompanhamentoSiltDetDTO>();

                using (AcompanhamentoSiltBLL oBLL = new AcompanhamentoSiltBLL())
                {

                    retorno = oBLL.AcompanhamentoSiltTransacaoDet(DT_INCLUSAO);
                }
                var resp = Request.CreateResponse<List<AcompanhamentoSiltDetDTO>>(HttpStatusCode.OK, retorno);
                return resp;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
  • Error on which line? Tries to add Session this way Httpcontext.Current.Session["DT_INCLUSAO"]

  • This is MVC or Web API?

  • tried it the way above but it didn’t work either, this controller ta inside an API, I’m almost sure q is why it doesn’t work.

1 answer

1


Unable to access context via HttpContext.Current in a ApiController.

To access the context use the following form:

var context = Request.Properties["MS_HttpContext"] as HttpContext;

Source

Note: Property name may have changed, check other properties on Request.Properties

Browser other questions tagged

You are not signed in. Login or sign up in order to post.