C# 用户登录.net 4.5后的身份验证
我需要一些帮助,我正在尝试在用户登录后识别他们。除了where子句之外,我的代码工作正常。 如何识别用户,我基本上是想说UserName==loginName在哪里给我完整的记录。 然后从记录中我可以拿出车库ID,非常感谢任何帮助或指点C# 用户登录.net 4.5后的身份验证,c#,C#,我需要一些帮助,我正在尝试在用户登录后识别他们。除了where子句之外,我的代码工作正常。 如何识别用户,我基本上是想说UserName==loginName在哪里给我完整的记录。 然后从记录中我可以拿出车库ID,非常感谢任何帮助或指点 private void FindGarageID() { System.Security.Principal.WindowsIdentity identity = Context.Request.LogonUserIdentity;
private void FindGarageID()
{
System.Security.Principal.WindowsIdentity identity = Context.Request.LogonUserIdentity;
string loginName = identity.Name;
using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
{
garage = (from r in dbcontext.AspNetUsers
where r.UserName == loginName
select r).FirstOrDefault();
if (!garage.GarageID.Equals(null))
{
garageID = (int)garage.GarageID;
}
else
{
garageID = 1;
}
}
下面是我将如何做到这一点。我将创建一个名为Session的静态类。这只是为我封装了会话变量的访问
public static class Session
{
public static string UserName
{
get { return (JsonWhereClause)HttpContext.Current.Session["UserName"]; }
set { HttpContext.Current.Session["UserName"] = value; }
}
}
然后当用户登录时,我会这样做
Session.UserName = ""//User inputed username
这将使您的代码变成这样
private void FindGarageID()
{
string loginName = Session.UserName;
using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
{
garage = (from r in dbcontext.AspNetUsers
where r.UserName == loginName
select r).FirstOrDefault();
if (!garage.GarageID.Equals(null))
{
garageID = (int)garage.GarageID;
}
else
{
garageID = 1;
}
}
请注意,该会话仅在Web服务器上可用,因此如果您有一个服务,则需要将用户名传递给该服务。因此,多了解一些信息就好了。如果您使用的是identity,我假设这是一个内部网站?不,这是一个网站,我是否使用了错误的代码?当您使用active directory验证用户时,会使用WindowsIdentity。如果这是一个公共网站,那么当用户登录时,在会话中输入用户名,然后在您的查询中使用该用户名。好的,谢谢尝试:)