0

I want to set the date into a session, but it's giving me a null value.

Here is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using PowerBICustomPage.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System.Security.Claims;
using System.Web;

namespace PowerBICustomPage.Controllers.Api
{
    [Authorize]
    public class AccountController : ApiController, IRequiresSessionState
    {
        DataClassesDataContext _context;
        public AccountController()
        {
            _context = new DataClassesDataContext();
            
        }
  [AllowAnonymous]
        [HttpPost]
        public IHttpActionResult Login(LoginViewModel model)
        {
                    var userinfo = _context.Users.SingleOrDefault(l => l.UserName == model.UserName);
                    DateTime DateExp = userinfo.DateExpiration.Value;
                
                    var date = DateExp.ToString("dd/MM/yyyy HH:mm:ss");
                    HttpContext.Current.Session["expired"] = date;// THIS LINE RETURNS NULL
        }
    }
}

I just shortened my code so it won't look messy. Also Intellisense is not picking up ViewBag or Session[""] and I don't know why.

I've tried this

HttpContext context = HttpContext.Current;
context.Session["expired"] = DateExp.ToString("dd/MM/yyyy HH:mm:ss");

But it's still returning a null value

weboshi
  • 1
  • 2

1 Answers1

0

HttpContext.Current.Session["expired"] = date;// THIS LINE RETURNS NULL

The line is not returning null, it isn't returning anything. It is an assignment so it won't return anything. You need to return the correct view at the end of the action.

Either:

return View();

Or:

return View("NameOfViewToLoad");

Should be added to the end of the method.

Note: Login() allows people to call it without being authenticated but doesn't seem to carry out any authentication. It is advisable to change the method for security reasons - a simple password check at least

YungDeiza
  • 3,128
  • 1
  • 7
  • 32