大家好,我试图在不同的控制器之间使用Session共享对象值,我有点迷失了,因为我的网站中处理身份验证的方式未在任何文章中描述,也没有我可以参考的指南以跟进“如何”
无论如何,我有一个在其他具有“ BaseController.verifyAccess(string user,string password)”的控制器之间共享的BaseController,它的作用是,检查用户的数据库是否可以访问View
BaseController.cs
public class User
{
public int ID { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
}
AccountController.cs
[HttpPost]
public ActionResult Login(FormCollection form)
{
User userTest = new User();
userTest.username = form["username"];
userTest.password = form["password"];
Session["username"] = userTest.username;
if (verifyAccess(userTest.username, userTest.password))
{
return RedirectToAction("../LoggedIn");
}
else
{
return RedirectToAction("../Login");
}
}
如何Session["username"] = userTest.username;
在其他Controller中工作?
例如
SomeController.cs
[HttpPost]
public ActionResult MyAwesomeView(FormCollection form)
{
Project.Models.MyAwesomeModel thisModel = new Models.MyAwesomeModel();
thisModel._info1 = form["txtInfo1"];
thisModel._info2 = form["txtInfo2"];
thisModel._info3 = form["txtInfo3"];
thisModel._info4 = form["txtInfo4"];
thisModel._user = System.Web.HttpContext.Current.Session["username"].ToString();
return View(modelPagosRecibidos);
}
尽管调试thisModel._user
为空,但我想我做错了很多,如果有人对我的代码感到感叹,我深表歉意。无论如何,希望对在控制器上获取Session值获得帮助和指导,在此先感谢大家!
请尝试以下代码段。一旦分配了信息,Application Session
就可以访问Client Controller
该会话中的所有内容,如我所展示的示例。
public class DeshboardController : Controller
{
// GET: Admin
public ActionResult Index()
{
string roleid = (string)Session["user_role_id"];
string userid = (string)Session["user_au_id"];
string companyId = (string)Session["company_id"];
string accessToken = (string)Session["AccessToken"];
string ConName = "Deshboard";
string ActionName = "index";
if (string.IsNullOrEmpty(roleid) || string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(companyId))
{
Response.Redirect("/Login/Index");
}
bool permission = CoreRules.UserPermission(roleid, userid, ConName, ActionName, accessToken);
if (!permission)
{
try
{
Response.Redirect("/Error/Index");
}
catch (Exception ex)
{
Response.Redirect("/Login/Index");
}
}
return View();
}
}
此外,您可以按Web.config
以下方式在文件中设置令牌的有效性
<appSettings>
<add key="TokenExpiry" value="45" />
</appSettings>
我将令牌时间设置为45分钟。您可以根据需要进行自定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句