ASP.NET MVC在Ajax中获取Exception消息

Kri*_*s-I 5 ajax asp.net-mvc jquery

我有一个动作:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    ...
    if (model.MyCondition == true)
        throw new Exception("MyMessage);
    ....
}
Run Code Online (Sandbox Code Playgroud)

我想在Ajax端获得消息"MyMessage":

onSuccess: function () {
...
},
onError: function (jqXHR, textStatus, errorThrown) {
//I'd like get "MyMessage" here
}
Run Code Online (Sandbox Code Playgroud)

一个想法如何做到这一点?当我检查调试器时,我没有看到我的字符串.

Kam*_*yar 8

实现错误属性是一种好方法.此外,我通常不抛出异常,但根据错误返回状态代码.您可以通过以下方式写入您的响应流并访问js XMLHttpRequest.responseText:

if (model.MyCondition == true)
{
    if (Request.IsAjaxRequest())
    {
        Response.StatusCode = 406; // Or any other proper status code.
        Response.Write("Custom error message");
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

在js中:

...
error: function (xhr, ajaxOptions, errorThrown) {
    alert(xhr.responseText);
}
Run Code Online (Sandbox Code Playgroud)