I need to have this code run for each of my actions in one of my controllers. How can I do this without having to copy the code for each of the actions? Is there an init method for the controller?
System.Web.HttpSessionStateBase Sess = HttpContext.Session;
string pid = (Sess["PID"] != null ? Sess["PID"].ToString() : "");
string LogonTicket = (Sess["LogonTicket"] != null ? Sess["LogonTicket"].ToString() : "");
Why don't you wrap this up into properties in a base controller?
class abstract YourControllerBase : Controller
{
public string Pid { get { ... } }
public string LogonTicket { get { ... } }
}
You have a couple options:
Use OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); }
I think although being abolutely correct, abstract classes and inheritance-based answers make an "asker" feel uncomfortable, since he is trying to work on an even simpler case then inheritace.
A short answer - just put the code into the constructor of the controller.
For example:
public HomeController: Controller {
private string _pid;
private string _logonTicket;
public HomeController() {
System.Web.HttpSessionStateBase Sess = HttpContext.Session;
_pid = (Sess["PID"] != null ? Sess["PID"].ToString() : "");
_logonTicket = (Sess["LogonTicket"] != null ? Sess["LogonTicket"].ToString() : "");
}
//REST OF YOUR CONTROLLER CODE
}
Now you can access _pid
and _logonTicket
from controller action's code.
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.