Home > Net >  The controller class constructor, read out cookies, what's the problem
The controller class constructor, read out cookies, what's the problem

Time:12-15


Later, because of the need to read the user cookie value as a global variable for master page, such as the head address, but found in a constructor, is not generated, no matter have cookie content, are said to be null, but also not allowed, errors, for some reason, please people
The code is as follows:
 public class BaseController: Controller 
{




//GET: Base [the Authorize]


Public BaseController ()
{


String ImageUrl=Common. The ImageUrl;
String cookiename=Request. Cookies [". Cookiename "];
If (cookiename!=null & amp; & Cookiename. Length & gt; 0)
{
String AdminFace=User. FindFirst (" FacePhoto "). The Value;
. String AdminTrueName=User Identity. The Name;
ViewBag. AdminFace=ImageUrl + AdminFace;
ViewBag. AdminTrueName=AdminTrueName;
}






}


Run error:
System. NullReferenceException: "Object reference not set to an instance of an Object."

But it can put into a specific page, normal read
 
Public IActionResult Index ()
{


String ImageUrl=Common. The ImageUrl;
String cookiename=Request. Cookies [". AspNetCore. JPTABCOOKIE "].
If (cookiename!=null & amp; & Cookiename. Length & gt; 0)
{
String AdminFace=User. FindFirst (" FacePhoto "). The Value;
. String AdminTrueName=User Identity. The Name;
ViewBag. AdminFace=ImageUrl + AdminFace;
ViewBag. AdminTrueName=AdminTrueName;
}

return View();
}


CodePudding user response:

In
 protected override void OnActionExecuting (ActionExecutingContext filterContext) 

CodePudding user response:

The constructor as far as possible don't do operation, only do variable initialization, you can try to create a new static class, create a static method in the class, need to use to call again,

CodePudding user response:

A cookie is generally in page read
  •  Tags:  
  • C#
  • Related