【问题标题】:ASP.NET Web Pages (Razor) Exit Code BlockASP.NET 网页 (Razor) 退出代码块
【发布时间】:2015-05-28 16:31:17
【问题描述】:

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

页面加载前:

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

如果用户 ID 不存在,则显示错误消息然后跳过密码验证并让 html 页面的其余部分(正文、页脚)加载。我目前的解决方案是使用 VB 特定的 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

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

【问题讨论】:

  • 听起来你在混淆ControllerView
  • 这不是 MVC。它是 ASP.NET 网页。就像 PHP 和 Classic ASP。
  • 哦,难怪我读起来觉得很脏。

标签: asp.net .net vb.net razor asp.net-webpages


【解决方案1】:

简短的回答可以使用函数:

@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

【讨论】:

  • 我想过这样做。使用结果来指示发生了哪个错误。但是,如果我有更多验证,请说 10 多个不同的验证。在下一次验证之后,我必须输入: if string.isnullorempty(result) 9 次。如果第一次验证结果不为空,则下一个 if string.isnullorempty 语句仍会再执行 9 次,我认为这仍然不是一个优雅的解决方案。
  • @AlbertTobing 使用 return 语句编辑以避免 null 或空检查,您可以在函数内部进行检查并仅在一个地方测试 null 或空
  • 我找到了解决方案!部分感谢您有关如何将功能放入网页的信息。
  • @AlbertTobing 你能添加你的答案吗?
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多