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

时间:2016-11-25 17:11:54

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

我正在尝试让用户帐户管理工作在我正在构建的asp.net mvc5网站上。新用户创建大部分都在工作,但是在创建用户期间抛出异常时,我遇到显示错误的问题。捕获/处理异常并在AdminController的Create()操作中向ModelState对象添加错误消息,但是当我返回到Create视图时,不会显示错误。

其他类型的用户创建错误(不会导致抛出异常)会正确显示。作为旁注,当问题发生时,我的浏览器上的“微调器”永远不会停止,表明启动创建操作的帖子从未完成。如果我点击浏览器中的菜单,我会导航到新页面并且微调器消失。

在以下情况下正确显示且与例外无关的Create()错误发生在:

var newUserCreateResult = UserManager.Create(newUser, password)

返回:

newUserCreateResult.Succeeded == false

与异常关联且正确显示的create()错误发生在:

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

抛出异常。我正在使用SmtpMailService,当无法访问电子邮件服务器或smtp帐户配置不正确时抛出异常。

我尝试过的一些事情:

  1. @ Html.ValidationSummary(真)
  2. 通过迭代ModelState手动创建错误列表 “创建”视图中的错误。调试器指示代码执行, 但它仍然无法显示。
  3. 我的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);
        }
    

    我的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>
    }
    

1 个答案:

答案 0 :(得分:0)

这个问题神秘地消失了(我重新启动电脑后?)。它现在应该从异常中发布错误。