如何在登录受限时向用户返回正确的错误消息

时间:2016-11-17 17:05:58

标签: c# asp.net asp.net-mvc exception asp.net-mvc-5

我是ASP.Net Web开发的新手,在登录受限制时,我无法处理异常。 问题:我有所有者登录和租户登录。现在所有者可以限制登录租户。但是当登录受到限制时,我想向租户显示他们的凭证是正确的但登录是受限制的。

以下是我迄今为止所尝试的内容。

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LoginSubmit(LoginMV userData)
{
    if (userData != null)
    {
        UserMV authenticatedUser = AuthenticateTenant(userData.Username, userData.Password);
        if (authenticatedUser == null)
        { 
              ModelState.AddModelError("Invalid credentials"); 
        }
        else
        {
           //Do the login
        }
    }

    return View("Login", userData);
}

来自API的用户数据

private static UserMV AuthenticateTenant(string username, string password)
        {
            Res response = mdlAPI.AuthenticateTenant(username, password);
        try{
            response.Validate(username);
           }

        UserMV result = new UserMV()
            {
                DisplayName = response.objTenant.LastName + ", " + response.objTenant.FirstName
            };
            return result;
        }

FYI API响应为response.ResultCode = Restricted

验证

   public static void Validate(this Res response, string username)
            {
                if (response.ResultCode != Enumerations.AuthResultCode.Successful)
                {
                    string additionalDetails = "";
                    if (response.ResultCode == Enumerations.AuthResultCode.Restricted)
                    {
                        additionalDetails = "Login Restricted.";
                    }
                    throw new ValidationException(additionalDetails);
                }
            }

所以在上面的方法中additionalDetails设置为“Login Restrcited” 并调用ValidationException。此外,由于引发了异常,因此不会在AuthenticateTenant function中创建UserMV对象。

ValidationException

public class ValidationException : Exception
{
    public ValidationException(string message) : base (message)
    { }
}

在所有这些之后,代码序列返回到Controller。由于userMV为NULL,显示的错误消息是“无效凭据”。我错过了什么。

我在ValidationException类中正确获取了异常。我是否需要做其他事情才能向用户显示异常。我是初学者,所以原谅我的编码标准。请指导我还需要做些什么才能向租户展示“附加细节”内容。

查看文件:

@using (Html.BeginForm("LoginSubmit", "Security", FormMethod.Post, new { id = "simLogin" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal-width-inherit">
        @Html.HiddenFor(model => model.ReturnUrl)

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label ignoreSpacing col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { @class = "form-control" } )
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label ignoreSpacing col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { @class = "form-control" } )
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Login" class="btn btn-default" />
            </div>
        </div>
    </div>
}

1 个答案:

答案 0 :(得分:2)

您似乎依赖于AuthenticateTenant()来检查您的凭据以及return身份验证结果。

但是,在内部,您正在调用Validate(),而这又会引发异常。该异常正在改变代码的控制流程。目前,唯一能够捕获它的代码是您拥有的某个错误过滤器,或者它已传播到IIS并且正在显示通用HTTP 500.

我建议不要在AuthenticateTenant()方法中抛出异常,而是返回null(或false,如果您愿意更改方法签名)。

一旦您重新控制了流量,您就可以依靠返回的结果正确地使用正确的消息来呼叫ModelState.AddModelError()