我设置web。登录用户配置如下:
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" defaultUrl="~/" timeout="20" slidingExpiration="true" />
</authentication>
<membership defaultProvider="SqlProvider">
<providers >
<clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ParsDataEntities" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="6" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
另一方面,用户的属性与具有四个模型的ViewModel相关:
public class CreateUsersViewModel
{
public EmployeePosition EmployeePositions { get; set; }
public Employee Employees { get; set; }
public UsersInfo UserInfos { get; set; }
public Department Departments { get; set; }
}
并且,我将当前用户的“名称”和“位置”显示为:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(string username, string password, bool remmeberme)
{
var db = new ParsDataEntities();
UsersInfoRepository BlUserInfo = new UsersInfoRepository();
CreateUsersViewModel UVM = new CreateUsersViewModel();
if (BlUserInfo.Exist(username, encryptString(password)))
{
var ViewModel = (from EP in db.EmployeePositions
join Dep in db.Departments on EP.DepID equals Dep.DepID
join E in db.Employees on EP.EmpID equals E.EmpID
join UI in db.UsersInfos on EP.EmpID equals UI.Usr_EmpID
where EP.DepID == Dep.DepID && EP.EmpID == E.EmpID && EP.EmpID == UI.Usr_EmpID
select new CreateUsersViewModel
{
EmployeePositions = EP,
Departments = Dep,
Employees = E,
UserInfos = UI,
}).Where(x => x.UserInfos.Usr_UserName == username).FirstOrDefault();
var name = ViewModel.Employees.EmpFirstName + ViewModel.Employees.EmpLastName;
var position = ViewModel.Departments.DepName;
FormsAuthentication.SetAuthCookie(name+"-"+position, remmeberme);
return RedirectToAction("/Index");
}
else
{
ViewBag.Message = "username or password is wrong";
}
return View();
}
在此阶段之前,用户将正确登录,“名称”和“位置”将显示为用户信息。
之后,我想获取当前用户的用户id。此字段是“UserInfo”中的主键。
我在另一个控制器(用于另一个视图)中使用此代码,但遇到错误:
string currentUserId = Convert.ToString(Membership.GetUser().ProviderUserKey);
错误是:
系统ArgumentException:“尝试
初始化系统。数据SqlClient。SqlConnection对象。价值观
为连接字符串提供的可能错误,或者
包含无效语法。”InnerException:ArgumentException:关键字
不支持:“元数据”。