MVC Handling a CorpId for the site

2019-02-20 17:47发布

问题:

I'm not sure I'm handling this the right way, but since I'm running into issues, I assume I'm not.

I have to have a corporation id sent in when loading the login screen.

Looks like this:

public ActionResult LogOn(string id)
{
  var sb = new StringBuilder();
  sb.AppendLine(string.Format("CorpID: {0}", id));

  if(ViewBag.CorpID != null)
    sb.AppendLine(string.Format("ViewBag.CorpID: {0}", ViewBag.CorpID));

  Guid corpIdGuid;
  if (!Guid.TryParse(id, out corpIdGuid) && string.IsNullOrEmpty(ViewBag.CorpID))
    return null;

  // the id passed in will take presidence over the 
  // viewbag unless it is blank then we use viewbag
  // one way or the other viewbag.corpid should not
  // be blank
  if(!string.IsNullOrEmpty(id))
    ViewBag.CorpID = id;

  // Session["CorpId"] = id;
  //Not a junk guid.. continue.
  return View();
}

I need this to establish what company we will be working with during this session.

The problem I am running into, is when the cookie timeout occurs, which is set to 10 minutes, it directs them back to this login and I have no corpid anymore.

I tried the viewbag and it's being reset.

I tried a cookie, but since it expires, the data is no longer there.

I tried a Profile Manager but since they are logged it, that puts me back to nothing.

How do I maintain this CorpId when the user has timed out and put back on the login screen? I need this information for each screen I have also.

Any input would be greatly appreciated!

回答1:

You need to create a separate cookie that identifies the Corporate ID that doesn't expire with user's session. Session["CorpId"] will expire with the user session and won't work.

var corpCookie = new HttpCookie("CorpID", id);
corpCookie.Expires = DateTime.Now.AddDays(30.0);
HttpContext.Current.Response.Cookies.Set(corpCookie);

Each time the user logs in, you could update the expiry to make it a sliding expiration. To retrieve the cookie value, use the following:

var corpID = HttpContext.Current.Request.Cookies.Get("CorpID").Value;