当我从 ajax 调用返回 HttpException() 时,我发现我得到了一个很大的 html 文本。
如果我在我的 Controller 中做这样的事情:
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 是“错误”
简单传回并显示来自 HTTP 异常的错误的最佳方法是什么?
最佳答案
不是在 Controller 中抛出异常,而是捕获它并为 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();
});
然后在您的 Controller 代码中捕获异常而不是抛出异常:
[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);
}
关于c# - 无论如何在 ajax 调用中从 asp.net-mvc 中的服务器端异常返回原始文本而不是 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8966842/