angularjs - 使用 angularjs 在 MVC .net 应用程序中维护会话
问题描述
我正在开发一个应用程序,如果用户在 db 中有帐户,则可以登录网站然后执行某些功能。其中一项功能涉及创建博客。该博客正在使用相同数据库的另一个项目应用程序中显示。现在,当用户在登录后创建博客时,我需要存储谁创建了博客才能做到这一点,我想出了两种方法。要么我继续将用户 ID 作为参数传递给每个页面 url,要么我可以创建一个会话以便在登录期间存储它。
我认为后者是一个更好的选择,但我对如何做到这一点有点迷茫。我正在创建一个 3 项目层应用程序。客户端在 angularjs 中完成。我的 c# 控制器仅用于将 json 数据传递到另一层,然后与另一层中的数据库通信。
项目文件太大,但我可以为它写一个示例代码。
html:
<div ng-app="Module">
<div ng-controller="AppController">
<input ng-model="user.Email" type="email"\>
<button type="button" ng-click="UserLogin()"\>
</div>
</div>
AngualrJs:
var app = angular.module('Module', []);
app.controller("AppController", function ($scope) {
$scope.loginchk = function () {
Post("/User/LoginValidation", $scope.user, false, $("#btnlogin")).then(function (d) {
if (d.Success) {
window.location.href = "/User/LoggedIn?emailId=" + $scope.user.Email;
}
ShowMessage(d);
});
}
})
控制器:
public JsonResult LoginValidation(LoginUser user) {
return Json((new userLogic()).LoginChk(user), JsonRequestBehavior.AllowGet);
}
业务逻辑层----------------
用户逻辑:
public Message LoginChk(LoginUser user) {
Message msg = new Message();
try {
Account userProfile = db.Accounts.Where(b => b.Email == user.Email).FirstOrDefault();
if (userProfile == null)
{
msg.Success = false;
msg.MessageDetail = "Account Email does not exist";
}
else
{
if (userProfile.password != user.Password)
{
msg.Success = false;
msg.MessageDetail = "Wrong Password";
}
else
{
msg.Success = true;
msg.MessageDetail = "Logged In";
}
}
}
catch(Exception ex)
{
msg.Success = false;
msg.MessageDetail = "DB connection failed.";
}
return msg;
}
现在我知道我可以像这样在控制器中创建一个会话变量,Session['Sessionname'] = user;
但我不确定它是否适用于我的应用程序,因为我有多个控制器,我仍然需要将它传递给它们。所以我看不到在每个控制器中维护会话变量的意义,即使它没有被使用。我该如何创建会话?
解决方案
您可以使用客户端 LocalStorage 保存用户 ID 并在必要时使用它,因为它将以纯文本格式保存,您可以加密并保存它。在这里查看如何使用 javascript 加密 https://stackoverflow.com/a/40478682/7262120
推荐阅读
- three.js - 如何修复 GLB/GLTF 导出器将单个网格导出为多个网格
- c - 使用函数的向量的平均值和最大值
- java - 覆盖方法的 Java 文档实践,其返回类型是被覆盖方法的返回类型的子类
- c - 试图为结构中的 void 指针赋值
- perl - 有人可以解释这个参考函数如何与这个 perl 子例程一起工作吗?
- matlab - 将函数与具有奇异点的两个变量集成的问题(MATLAB)
- nginx - 如何让 Nginx 等待线程池任务
- google-docs - 如果与单独列中的单元格完全匹配,则格式化列中的单元格
- regex - 用于匹配所有电子邮件 ID 的正则表达式
- django - 为自定义用户设置 django 注册(验证自定义用户的用户创建表单导致没有这样的表:app_appuser)