简体   繁体   English

Asp.net MVC5为什么Html.ValidationSummary(false)不显示异常错误?

[英]Asp.net MVC5 Why won't Html.ValidationSummary(false) display exception errors?

I am trying to get user account management working in an asp.net mvc5 website I am building. 我正在尝试让我正在建立的asp.net mvc5网站上的用户帐户管理工作。 New user creation is mostly working, but I am having a problem displaying errors when an exception is thrown during the creation of the user. 新用户的创建基本上可以正常工作,但是在创建用户期间引发异常时,显示错误会出现问题。 The exception is caught/handled and an error message is added to the ModelState object in the Create() action of my AdminController, but the error is not displayed when when I return to the Create view. 捕获/处理了异常,并且在我的AdminController的Create()操作中向ModelState对象添加了错误消息,但是当我返回到Create视图时,不会显示该错误。

Other types of user creation errors, that do not result in an exception being thrown, do display properly. 不会导致引发异常的其他类型的用户创建错误可以正确显示。 As a side note, when the problem occurs, a "spinner" on my browser never stops, indicating that the post that initiated the create action never completed. 附带说明,发生问题时,浏览器上的“旋转器”永远不会停止,这表明发起create动作的帖子从未完成。 If I click on a menu in the browser, I navigate to the new page and the spinner goes away. 如果单击浏览器中的菜单,则导航到新页面,微调框消失。

The Create() errors that display properly and are not associated with an exception occur when: 在以下情况下会出现正确显示且与异常无关的Create()错误:

var newUserCreateResult = UserManager.Create(newUser, password)

returns: 返回:

newUserCreateResult.Succeeded == false

The create() errors that are associated with an exception and do not display properly occur when: 与异常相关联且无法正确显示的create()错误在以下情况下发生:

await UserManager.SendEmailAsync(newUser.Id, "Reset Password", "Please confirm your account and reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

throws an exception. 引发异常。 I'm using an SmtpMailService and an exception is thrown when the email server cannot be reached, or the smtp account configuration is incorrect. 我使用的是SmtpMailService,当无法访问电子邮件服务器或smtp帐户配置不正确时,将引发异常。

Some things I've tried: 我尝试过的一些事情:

  1. @Html.ValidationSummary(true) @ Html.ValidationSummary(true)
  2. Manually creating the error list by iterating through the ModelState errors in the Create view. 通过遍历“创建”视图中的ModelState错误来手动创建错误列表。 The debugger indicates the code executes, but it still doesn't display. 调试器指示代码已执行,但仍不显示。

My Create() action: 我的Create()动作:

        // PUT: /Admin/Create
    [Authorize(Roles = "Admin")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    #region public ActionResult Create(CreateUserDTO createUserDTO)
    public async Task<ActionResult> Create(CreateUserDTO createUserDTO) {
        ApplicationUser newUser = null;
        try {
            if (createUserDTO == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var Email = createUserDTO.Email.Trim();
            if (Email == "") {
                throw new Exception("No Email");
            }
            // Create user
            newUser = new ApplicationUser { UserName = Email, Email = Email };
            var password = Membership.GeneratePassword(8, 3) + "aaZZ09";
            var newUserCreateResult = UserManager.Create(newUser, password);

            if (newUserCreateResult.Succeeded == true) {
                UserManager.AddToRole(newUser.Id, createUserDTO.SelectedRole);
                string code = await UserManager.GeneratePasswordResetTokenAsync(newUser.Id);
                code = HttpUtility.UrlEncode(code);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = newUser.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(newUser.Id, "Reset Password", "Please confirm your account and reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return Redirect("~/Admin");
            } else {
                // Html.ValidationSummary displays these errors correctly
                foreach (string msg in newUserCreateResult.Errors) {
                    ModelState.AddModelError(string.Empty, msg);
                }
            }
        } catch (Exception ex) {
            // Html.ValidationSummary DOESN NOT display these errors
            ModelState.AddModelError(string.Empty, ex.Message);
        }
        if (newUser != null) {
            UserManager.Delete(newUser);
        }
        createUserDTO.Roles = GetAllRolesAsSelectList();
        return View("Create", createUserDTO);
    }

My Create.cshtml view: 我的Create.cshtml视图:

    @model Nissan.Models.CreateUserDTO
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "Admin", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Create User</h4>
        <hr />
        @Html.ValidationSummary(false, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Email,
           htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email,
               new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "",
               new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Roles,
           htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedRole, (Model == null) ? null : Model.Roles);
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
                @Html.ActionLink("Cancel",
               "Index",
               null,
               new { @class = "btn btn-default" })
            </div>
        </div>
    </div>
}

This problem mysteriously disappeared (after I rebooted my PC?). 这个问题神秘地消失了(在重新启动PC后?)。 It's now posting errors from the exception as it should. 现在,它应该按照异常发布错误。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM