【问题标题】:Is there anyway to return raw text instead of html from a server side exception in asp.net-mvc on an ajax call?无论如何,在 ajax 调用中,asp.net-mvc 中的服务器端异常是否可以返回原始文本而不是 html?
【发布时间】:2012-01-23 03:14:35
【问题描述】:

当我从 ajax 调用返回 HttpException() 时,我发现我得到了一个很大的 html 文本。

如果我在我的控制器中做这样的事情:

   if (errors.Count > 0)
        {
            throw new HttpException(404, "This is my custom error msg");
        }

我想要一个很好的简单方法来解析 javascript 端的错误消息。现在,当我用类似这样的方式查看客户端的回调时

  function decodeErrorMessage(jqXHR, textStatus, errorThrown) {

我看到 jqxHR = "3", textStatus = 一个很长的 html 文档(带有调用堆栈和错误消息,errorThrown 是 "error"

简单地回传并显示来自 http 异常的错误的最佳方法是什么?

【问题讨论】:

标签: c# jquery ajax asp.net-mvc exception-handling


【解决方案1】:

不是在控制器中抛出异常,而是捕获它并为 AJAX 响应设置响应代码:

使用 JQuery 查看逻辑设置:

    $("#btnRefresh").live("click", function(e) {
        $.ajax({
            type: "POST",
            url: '@Href("~/Home/Refresh")',
            data: "reportId=@Model.Id"
        })
        .done(function(message) {
            alert(message);
        })
        .fail(function(serverResponse) {
            alert("Error occurred while processing request: " + serverResponse.responseText);
        });

        e.preventDefault();
    });

然后在您的控制器代码中捕获异常而不是抛出它:

    [HttpPost, VerifyReportAccess]
    public ActionResult Refresh(Guid reportId)
    {
        string message;

        try
        {
            message = _publisher.RequestRefresh(reportId);
        }
        catch(Exception ex)
        {
            HttpContext.Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            message = ex.Message;
        }

        return Json(message);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    相关资源
    最近更新 更多