Vb.net 使用表单身份验证登录MVC

Vb.net 使用表单身份验证登录MVC,vb.net,asp.net-mvc-4,model-view-controller,Vb.net,Asp.net Mvc 4,Model View Controller,我决定使用表单身份验证来登录用户,不幸的是,我在这方面遇到了一些问题。我想,如果用户登录正确,将他移动到某个特定的控制器,从这一点上,他可以检查其他控制器,如果他真的授权。当然,在所有控制器的方法中,都会检查用户是否真的通过了身份验证,对吗?这是本主题底部的主要问题和其他三个问题。请感谢您的支持 到目前为止,我的LoginController中有以下代码: Function Index() As ActionResult Return View() End Fun

我决定使用表单身份验证来登录用户,不幸的是,我在这方面遇到了一些问题。我想,如果用户登录正确,将他移动到某个特定的控制器,从这一点上,他可以检查其他控制器,如果他真的授权。当然,在所有控制器的方法中,都会检查用户是否真的通过了身份验证,对吗?这是本主题底部的主要问题和其他三个问题。请感谢您的支持

到目前为止,我的LoginController中有以下代码:

    Function Index() As ActionResult
        Return View()
    End Function

    'Action for POST method (login)
    <HttpPost>
    <AllowAnonymous>
    Function Index(ByVal user As tbLogin) As ActionResult
        Try
            If (ModelState.IsValid) Then
                If IsValid(user.Login, user.Password) Then
                    FormsAuthentication.SetAuthCookie(user.Id, False)
                    Return RedirectToAction("AfterLogin")
                Else
                    ViewData("Success") = "Login error"
                End If
            End If
        Catch ex As Exception
            Return RedirectToAction("Index", "Home")
        End Try
        Return View(user)

    End Function

  'Action for Show view after login
    <Authorize>
    Function AfterLogin() As ActionResult
            Return RedirectToAction("Index", "Home")
        End If
    End Function

 Function IsValid(Login As String, password As String) As Boolean
        Dim _isValid As Boolean = False

        Using dc = New woitgroup_transport.production_WojtgroupEntitesContext
            Dim user = dc.tbLogin.Where(Function(a) a.Login.Equals(Login) And a.Password.Equals(password)).FirstOrDefault()

            If Not IsNothing(user) Then
                If user.Password = password Then
                    _isValid = True
                End If
            End If

        End Using
        Return _isValid
    End Function
这应该只返回false/true,但为了获得user.Id,我对其进行了重构,以获得这一信息,并将其传递给FormsAuthentication.SetAuthCookie(userId,false)。我正在寻找比现在更好的方法:

Function GetUserIdIfValid(Login As String, password As String) As Object
        Dim _getuserId As Object = Nothing
        Using dc = New woitgroup_transport.production_WojtgroupEntitesContext
            Dim user = dc.tbLogin.Where(Function(a) a.Login.Equals(Login) And a.Password.Equals(password)).FirstOrDefault()

            If Not IsNothing(user) Then
                If user.Password = password Then
                    _getuserId = user.Id
                End If
            End If
        End Using
        Return _getuserId
    End Function
问题2: 是的,您可以在web.config中设置登录表单,请参见问题4

第三项问题:

如果需要从控制器中获取用户,请使用控制器的user属性。如果您从视图中需要它,我会在ViewData中填充您特别需要的内容,或者您可以调用User,因为我认为这是ViewPage的一个属性

第四项问题。您可以在Web.config文件中设置登录用户的超时。我的看起来像这样:

 <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="1440" /> <!--1440Min = 24Hours-->
    </authentication>
.....
 </system.web>
所以只有auth。允许用户访问Employes Controlelr。如果他们没有权限,他们将被重定向到登录页面

第五个问题是正确的,但您需要重定向到视图,而不是仅仅传递视图

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        //Important part
        return RedirectToAction("Index", "ErrorLogs");
    }
我希望有帮助

编辑(讨论)

//This is the model which is used as a object to transfer data from View to Controller. Itself contains a method named Validate which is validating the user against Ad for ex.
public class tbLogin
{
    public string UserId { get; set;}
    private string Password { get; set;}

    public tbLogin(string uId, string pw)
    {
        this.UserId = uId;
        this.Password = pw;
    }

    public boolean Validate()
    {
        if(String.IsNullOrEmpty(UserId) || String.IsNullOrEmpty(Password)) { return; }
        //Validate user against Active Directory for ex.    
        return true;
    }
}


//This is your method in your account controller. It gets the data from the view and calls the validation method in the model
//Post
Public ActionResult Index(tbLogin user)
{

    if (!ModelState.IsValid)
    {
        return View(user);
    }

    if(user == null) 
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    try
    {
        if(user.Validate())
        {
            FormsAuthentication.SetAuthCookie(user.UserId, False);
            return RedirectToAction("AfterLogin");
        }
        else
        {
            //ViewData("Success") = "Login error"
        }
    }
    catch(Exception ex)
    {
         //Handle Expetion and redirect to Home-index
         return  RedirectToAction("Index","Home");
    }

    return View(user);
}

我还是有些困惑。我将超时设置为“5”,之后我就可以使用这个程序了——并没有重定向到登录页面。我不知道的第二件事;我不知道如何使它工作-正如您所看到的,我正在将user.Id添加到我的cookie中:FormsAuthentication.SetAuthCookie(user.Id,False)。现在在另一个控制器中如何访问此值-您可以显示为asnwer吗?请查看我的更新答案。使舒尔u已将用户指示设置为[授权]的控制器的属性设置为您只需在控制器中调用“user.Identity.GetUserName()”(我有此属性的位置:)。User.Identity.GetUserName()-没有类似的方法(GetUserName)。。。如何访问User.Id?在您的用户之间。Id是“User.Identity.GetUserName()”。使用此方法时,通常设置用户名而不是ID
 <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="1440" /> <!--1440Min = 24Hours-->
    </authentication>
.....
 </system.web>
 [Authorize]
 public class EmployeeController : Controller
 {
       private ActionResult Index()
        {
            return View("You are allowed to see this page, because you are logged-in");
        }
 }
    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        //Important part
        return RedirectToAction("Index", "ErrorLogs");
    }
//This is the model which is used as a object to transfer data from View to Controller. Itself contains a method named Validate which is validating the user against Ad for ex.
public class tbLogin
{
    public string UserId { get; set;}
    private string Password { get; set;}

    public tbLogin(string uId, string pw)
    {
        this.UserId = uId;
        this.Password = pw;
    }

    public boolean Validate()
    {
        if(String.IsNullOrEmpty(UserId) || String.IsNullOrEmpty(Password)) { return; }
        //Validate user against Active Directory for ex.    
        return true;
    }
}


//This is your method in your account controller. It gets the data from the view and calls the validation method in the model
//Post
Public ActionResult Index(tbLogin user)
{

    if (!ModelState.IsValid)
    {
        return View(user);
    }

    if(user == null) 
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    try
    {
        if(user.Validate())
        {
            FormsAuthentication.SetAuthCookie(user.UserId, False);
            return RedirectToAction("AfterLogin");
        }
        else
        {
            //ViewData("Success") = "Login error"
        }
    }
    catch(Exception ex)
    {
         //Handle Expetion and redirect to Home-index
         return  RedirectToAction("Index","Home");
    }

    return View(user);
}