简体   繁体   English

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

[英]How to return correct error message to User when log in is restricted

I am new to ASP.Net web development and I am stuck in handling the exceptions when log in is restricted. 我是ASP.Net Web开发的新手,当登录受到限制时,我只能处理异常。 Question: I have owner log in and tenant log in. Now owner can restrict the log in for Tenant. 问题:我具有所有者登录和租户登录。现在,所有者可以限制租户的登录。 But when the log in is restricted I want to show to the tenant that their credential is correct but log in is restricted. 但是,当登录受到限制时,我想向租户显示他们的凭据正确,但是登录受到限制。

Below is what I have tried till now. 以下是我迄今为止尝试过的方法。

Controller 调节器

[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);
}

User data from API 来自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 is response.ResultCode = Restricted . FYI API响应为response.ResultCode = Restricted

Validate 验证

   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);
                }
            }

So in the above method additionalDetails get set to "Login Restrcited" and the ValidationException is called. 因此,在上述方法additionalDetails被置为“登录Restrcited”和ValidationException被调用。 Also, since the exception is raised the UserMV object will not get created in the AuthenticateTenant function . 另外,由于引发了异常,因此不会在AuthenticateTenant function创建UserMV对象。

ValidationException ValidationException

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

After all of this the sequence of code returns to the Controller. 完成所有这些操作后,代码序列将返回到控制器。 As the userMV is NULL the error message that gets displayed is "Invalid credentials". 由于userMV为NULL,因此显示的错误消息为“无效凭据”。 Have I missed something. 我错过了什么吗?

I am getting the exception properly in ValidationException class. 我在ValidationException类中正确获取了异常。 Do I need to do something else for the exception to be displayed to the user. 我是否需要做其他事情才能将异常显示给用户。 I am a beginner so pardon my coding standards. 我是一个初学者,请原谅我的编码标准。 Please guide me what else I need to do to display the 'additional detail` stuff to the tenant. 请指导我要向租户显示“其他详细信息”的其他操作。

View File: 查看文件:

@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>
}

You seem to be relying on the AuthenticateTenant() to check the credentials for you and also to return the authentication result. 您似乎在依靠AuthenticateTenant()来检查您的凭据并return验证结果。

But, internally you're calling Validate() that in turn is throwing an exception. 但是,在内部,您正在调用Validate() ,而后者又引发异常。 That exception is changing the control flow of the code. 那个例外改变了代码的控制流程。 Currently, the only code that seems to catch it is either some error filter you have or it's propagated down to IIS and the generic HTTP 500 is being displayed. 当前,似乎唯一可以捕获到该错误的代码是您拥有的某些错误筛选器,或者已向下传播到IIS,并且正在显示通用HTTP 500。

I would suggest not to throw an exception as part of the AuthenticateTenant() method but rather return a null (or false , if you're willing to change the method signature). 我建议不要在AuthenticateTenant()方法中抛出异常,而应返回null (或者,如果您愿意更改方法签名,则返回false )。

Once you're back in control of the flow, you can rely on the returned result to rightfully call ModelState.AddModelError() with the proper message. 一旦恢复了对流程的控制,就可以依靠返回的结果正确调用ModelState.AddModelError()并带有适当的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 由于用户不存在/密码/用户名正确而导致尝试登录网站失败时如何返回消息? - How to return a message when a try to login to the website failed, because the user does not exist/password/username arent correct? 如何将错误消息从C#属性设置器“返回”给用户? - How to “return” an error message from a C# property setter to the user? 写入Windows事件日志时出现错误消息 - Error message when writing to the Windows Event Log 如何返回特定的错误信息 - how to return specific error message 提示用户安装正确 dotnet 版本的错误信息不正确 - The error message that prompts user to install the correct dotnet version is incorrect 当includeExceptionDetailInFaults =“ false”时返回自定义错误消息 - Return custom error message when includeExceptionDetailInFaults=“false” 当消息传输到错误队列时,如何挂接到NServiceBus以写入日志文件? - How do I hook into NServiceBus to write to a log file when a message is transferred to the error queue? 如何返回带有详细错误消息的错误? - How to return an error with detailed error message? 如何检测用户何时切换到登录屏幕? - How to detect when the user switches to the Log On screen? 如何将自定义错误消息返回给View? - How to return custom error message to View?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM