ASP.NET 网页 (Razor) 退出代码块

ASP.NET Web Pages (Razor) Exit Code Block

有人知道如何在 VB 语言的 ASP.NET 网页 (Razor) 中退出代码块而不中断页面加载吗?假设我有一个按以下顺序执行的登录机制:

页面加载前:

  1. 检查用户id是否存在。
  2. 检查密码是否匹配。

如果用户 ID 不存在,则显示错误消息,然后跳过密码验证并加载 html 页面的其余部分(正文、页脚)。我目前的解决方案是使用 VB specific GoTo.. 我认为很难看的声明。有人有更优雅的解决方案吗?下面是一个简单的示例代码:

@Code
dim login As New clsLogin 'assume this class handles login validation
dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user

'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
    @<p>User does not exist !</p>
    GoTo skip
End If

'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
    @<p>Password Mismatch !</p>
    GoTo skip
End If

'Passes all validation, display success message
@<p>Login Successful !</p>

skip:
End Code

我试图用 return 语句替换 GoTo 语句。但是,它也停止了页面加载。我在显示任何 HTML 之前放置验证服务器代码,如果我使用 return 语句,它不会显示 HTML 页面。任何想法?提前致谢。

简答可以使用函数:

@Functions


function Check(byval inputUserID as integer, byval inputPwd as string) as string
dim login As New clsLogin 'assume this class handles login validation
dim result as string = string.Empty

'First, check if that ID exist in database
if login.userExist(inputUserID) = false then
    return "User does not exist !"

End If


'If ID exist, check if password match
if login.checkPwd(inputUserID, inputPwd) = false then
    return "Password Mismatch !"
End If

return result

end function
End functions

@Code

dim inputUserID As String 'this variable hold user id entered by user
dim inputPwd As String 'this is password entered by user

dim msg = @Check(inputUserID,inputPwd)
'Passes all validation, display success message
if string.isnullorempty(msg) then
    msg = "<p>Login Successful !</p>"

end if
@msg
End Code

无论阅读您的评论似乎您正在寻找一个优雅且可持续的解决方案,因此我认为您可以使用松散耦合的方式来解决您的问题 ValidationManager:


VB(用Telerik code converted翻译)


Public Interface ILoginProvider
    Function UserExist(inputUserID As Integer) As Boolean
    Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
End Interface

Public Class LoginProvider
    Implements ILoginProvider
    Public Function UserExist(inputUserID As Integer) As Boolean
        Return True
    End Function
    Public Function CheckPwd(inputUserID As Integer, inputPwd As String) As Boolean
        Return True
    End Function
End Class

Public Class ValidationResult
    Public Property Result() As Boolean
        Get
            Return m_Result
        End Get
        Set
            m_Result = Value
        End Set
    End Property
    Private m_Result As Boolean
    Public Property ResultMessage() As String
        Get
            Return m_ResultMessage
        End Get
        Set
            m_ResultMessage = Value
        End Set
    End Property
    Private m_ResultMessage As String
End Class

Public MustInherit Class Validator
    Protected _provider As ILoginProvider
    Protected _inputUserID As Integer
    Protected _inputPwd As String

    Public Sub New(provider As ILoginProvider, inputUserID As Integer, inputPwd As String)
        _provider = provider
        _inputPwd = inputPwd

        _inputUserID = inputUserID
    End Sub
    Public MustOverride Function Validate() As ValidationResult
End Class

Public Class UserExistenceValidator
    Inherits Validator
    Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)

        MyBase.New(provider, inputUserID, inputPwd)
    End Sub

    Public Overrides Function Validate() As ValidationResult
        Dim result = New ValidationResult()
        Dim check = _provider.UserExist(_inputUserID)
        result.Result = check
        If Not check Then
            result.ResultMessage = "User Doesn't exist"
        End If

        Return result
    End Function
End Class

Public Class UserPasswordValidator
    Inherits Validator
    Public Sub New(provider As LoginProvider, inputUserID As Integer, inputPwd As String)

        MyBase.New(provider, inputUserID, inputPwd)
    End Sub

    Public Overrides Function Validate() As ValidationResult
        Dim result = New ValidationResult()
        Dim check = _provider.CheckPwd(_inputUserID, _inputPwd)
        result.Result = check
        If Not check Then
            result.ResultMessage = "Wrong Password"
        End If

        Return result
    End Function
End Class

Public Class ValidationManager
    Private _validators As List(Of Validator)
    Public Sub New()
        _validators = New List(Of Validator)()
    End Sub

    Public Function Validate() As ValidationResult
        Dim result As ValidationResult = Nothing
        For Each item As var In _validators
            result = item.Validate()
            If Not result.Result Then
                Return result
            End If
        Next

        Return New ValidationResult() With { _
            Key .Result = True, _
            Key .ResultMessage = "Successfull validated" _
        }
    End Function
End Class

C#


  public interface ILoginProvider
  {
    bool UserExist(int inputUserID);
    bool CheckPwd(int inputUserID, string inputPwd);
  }

  public class LoginProvider: ILoginProvider
  {
    public bool UserExist(int inputUserID)
    {
      return true;
    }
    public bool CheckPwd(int inputUserID, string inputPwd)
    {
      return true;
    }
  }

  public class ValidationResult
  {
    public bool Result { get; set; }
    public string ResultMessage { get; set; }
  }

  public abstract class Validator
  {
    protected ILoginProvider _provider;
    protected int _inputUserID; 
    protected string _inputPwd;

    public Validator(ILoginProvider provider, int inputUserID, string inputPwd)
    {
      _provider = provider;
      _inputPwd = inputPwd;
      _inputUserID = inputUserID;

    }
    public abstract ValidationResult Validate();
  }

  public class UserExistenceValidator : Validator
  {
    public UserExistenceValidator(LoginProvider provider,int inputUserID, string inputPwd): base(provider,inputUserID, inputPwd)
    {

    }

    public override ValidationResult Validate()
    {
      var result = new ValidationResult();
      var check = _provider.UserExist(_inputUserID); 
      result.Result = check;
      if(!check)
        result.ResultMessage = "User Doesn't exist";

      return result;
    }
  }

  public class UserPasswordValidator : Validator
  {
    public UserPasswordValidator(LoginProvider provider, int inputUserID, string inputPwd)
      : base(provider, inputUserID, inputPwd)
    {

    }

    public override ValidationResult Validate()
    {
      var result = new ValidationResult();
      var check = _provider.CheckPwd(_inputUserID, _inputPwd);
      result.Result = check;
      if (!check)
        result.ResultMessage = "Wrong Password";

      return result;
    }
  }

  public class ValidationManager
  {
    List<Validator> _validators;
    public ValidationManager()
    {
      _validators = new List<Validator>();
    }

    public ValidationResult Validate()
    {
      ValidationResult result = null;
      foreach (var item in _validators)
      {
        result = item.Validate();
        if(!result.Result)
          return result;
      }

      return new ValidationResult(){Result = true,ResultMessage="Successfull validated" };
    }
  }

使用


@Function Check() As string

  Dim login As New clsLogin 'assume this class handles login validation
  Dim inputUserID As String 'this variable hold user id entered by user
  Dim inputPwd As String 'this is password entered by user


  Dim login As New LoginProvider()
  Dim validators = New List(Of Validator)()
  validators.Add(New UserExistenceValidator(login, 1, "test1"))
  validators.Add(New UserPasswordValidator(login, 1, "test1"))

  Dim manager = New ValidationManager(validators)
  Dim result = manager.Validate()
  return string.format("<p>{0}</p>",result.ResultMessage)


 End Function


  @Code

    @Check()

  End Code

找到了!感谢 InvernoMuto 向我展示如何在网页内定义函数。

首先我创建了一个 class 来保存登录结果,如果登录失败可以提供原因。

Class LoginResult
    Public Property LoginSuccess As Boolean
    Public Property Reason As String
End Class

然后我创建了以下用于登录验证的函数

@Functions
    Function CheckLogin(User As String, Pwd as String) As LoginResult
        dim login As New clsLogin
        Dim res as New LoginResult

        res.LoginSuccess = True

        if login.userExist(inputUserID) = false then
            res.LoginSuccess = False
            res.Reason = "User does not exist !"
            return res
        end if

        if login.checkPwd(inputUserID, inputPwd) = false then
            res.LoginSuccess = False
            res.Reason = "Password mismatch !"
            return res
        end if

        return res
    End Function
End Functions

然后在登录 HTML 页面上调用以下代码:

dim lr as LoginResult
lr = CheckLogin("someone", "password")

if lr.LoginSuccess = True then
    @<p>Login Success !</p>
else
    @<p>Error: @lr.Reason</p>
end if