JsonResult返回HTML响应

时间:2013-05-30 22:35:03

标签: asp.net-mvc json jquery parse-error

我在控制器中使用此方法通过邮件重置用户的密码。

public JsonResult RecoverPasswordByEmail(string mail)
    {
        MembershipUser member = Membership.GetUser(Membership.GetUserNameByEmail(mail));
        string newPassword = System.Web.Security.Membership.GeneratePassword(14, 0);

        member.UnlockUser();

        if (!member.ChangePassword(member.ResetPassword(), newPassword))
        {
            return Json(new { Resultado = false, Excepcion = "Couldn't change password" }, JsonRequestBehavior.AllowGet);
        }

        System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("foo@bar.com");
        System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mail);
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
        message.Subject = "Forgot pass";
        if (member.IsLockedOut)
        {
            message.Body = "You're locked";
        }
        else
        {
            message.Body = "New password: " + newPassword;
        }
        var client = new System.Net.Mail.SmtpClient("my.smtpserver.com", 587)
        {
            Credentials = new System.Net.NetworkCredential("foo@bar.com", "12345"),
            EnableSsl = true
        };
        try
        {
            client.Send(message);
        }
        catch (System.Net.Mail.SmtpException ex)
        {
            return Json(new { Resultado = false, Excepcion = ex.Message }, JsonRequestBehavior.AllowGet);
        }
        return Json(new { Resultado = true }, JsonRequestBehavior.AllowGet);
    }

我使用jQuery从登录视图的对话框中的按钮执行ajax请求。

奇怪的是,我使用另一个控制器方法RecoverPassword,它使用用户名做同样的事情并且有效。使用firebug我看到RecoverPassword完成工作并返回带有结果的JSON,但RecoverPasswordByEmail使用一个大的html文档进行响应。

HTML的重要部分:

<div id="dialog">
    <h2>Retrieve Password</h2>

    @Html.Label("Mail:")<br/>
    @Html.TextBox("txtMail")
    <div id="loading">
        <br/><img class="displayed" src="@Url.Content("~/Content/Images/Ajax/ajax-loader3.gif")" alt="loading" /><br/>
        @Html.Label("Error")
    </div>
    <br/><br/><input class="button" id="btnSendMail" type="submit" value="Get new password" />

<div>
        <a href="#" id="showDialog">Recuperar contraseña</a>
    </div>

</div>

和js:

$(document).ready(function(){

    var requestMail;
    $('#btnSendMail').button();
    $('#loading').hide();
    $("label[for=Error]").text("");

    $('#btnSendMail').click(function (event) {
        event.preventDefault();
        var mail = $("#txtMail").val();
        if (mail.length > 0) {
            if (requestMail && requestMail .readystate != 4) {
                requestMail .abort();
            }
            $('#loading').show();
            $('input[id="btnSendMail"]').attr('disabled', 'disabled');
            requestCorreo = $.ajax({
                url: '/Users/RecoverPasswordByEmail',
                type: 'POST',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                timeout: 8000,
                data: { Email: mail },
                success: function (response) {
                    if (response.Result) {
                        $("label[for=Error]").text('New password has been sent to: ' + mail);
                    }
                    else {
                        alert(response.Result + ' ' + response.Exception);
                    }
                },
                error: function (xhr, textStatus, thrownError) {
                    if (textStatus === "timeout") {
                        alert("got timeout");
                    }
                    else {
                        alert(xhr.status + ' ' + textStatus + ' ' + thrownError);
                    }
                },
                complete: function () {
                    $('#loading').hide();
                    $('input[id="btnSendMail"]').removeAttr('disabled');
                }
            });
        }
        else {
            $("label[for=Error]").text("Insert a valid email");
        }

        requestCorreo.done(function (msg) {
            alert(msg);
        });

        requestCorreo.fail(function (jqXHR, textStatus) {
            alert("Request failed: " + textStatus + " " + jqXHR.responseText);
        });
    });
});

1 个答案:

答案 0 :(得分:0)

返回的HTML是什么?我打赌你的方法是抛出一个异常,它被ASP.NET捕获,并返回一个错误页面而不是你方法中的JsonResult。

或者不是,HTML的内容将有助于更好地解决这个问题。

作为附注,您似乎没有在方法中的任何位置检查null - 并且您假设无论通过哪个电子邮件地址(可能确实是您的例外的来源),都会找到MembershipUser