如何从ASP.NET MVC操作返回错误

时间:2010-03-04 09:16:36

标签: jquery asp.net ajax asp.net-mvc

我使用ASP.NET MVC开发网站。我正在使用jquery来实现AJAX功能。在动作方法中,我想返回一些错误来表示输入不正确或者无法执行操作。在这种错误情况下,我希望调用jquery ajax错误处理程序,我可以在那里采取适当的操作。我还没有找到办法如何做到这一点。以下是我的行动方法。

在错误的情况下,我应该从Action发送什么才能触发jquery错误处理程序?

public ActionResult AddToFavourites(int entityId, string entityType)
    {

        if (!Request.IsAjaxRequest())
            throw new InvalidOperationException("This action can be called only in async style.");

        try
        {
            RBParams.EntityType typeOfFavourite = (RBParams.EntityType)Enum.Parse(typeof(RBParams.EntityType), entityType);
            string status = "";

            if (typeOfFavourite == RBParams.EntityType.BusinessEntity)
            {
                status = MarkFavouriteEntity(entityId);
            }
            else if (typeOfFavourite == RBParams.EntityType.Review)
            {
                status = MarkFavouriteReview(entityId);
            }
            else
            {
                throw new InvalidOperationException("The type of the entity is not proper");
            }

            return Content(status);

        }
        catch (Exception ex)
        {

            return Content("Error");
        }
    }

3 个答案:

答案 0 :(得分:23)

当操作未返回预期的状态代码时,将调用您的ajax错误处理程序。例如,如果未找到该操作,或者如果您抛出了您未处理的异常,它将触发。在您的情况下,如果您没有在操作中捕获错误,则会调用它(因为操作将返回500状态代码)。

但是,我不会这样做,因为这可能是一个预期的错误。当你成功并且出现错误时,我宁愿返回json。然后你可以指出它是否成功通话。像这样:

public ActionResult AddToFavourites(int entityId, string entityType)
{

    if (!Request.IsAjaxRequest())
        throw new InvalidOperationException("This action can be called only in async style.");

    try
    {
        RBParams.EntityType typeOfFavourite = (RBParams.EntityType)Enum.Parse(typeof(RBParams.EntityType), entityType);
        string status = "";

        if (typeOfFavourite == RBParams.EntityType.BusinessEntity)
        {
            status = MarkFavouriteEntity(entityId);
        }
        else if (typeOfFavourite == RBParams.EntityType.Review)
        {
            status = MarkFavouriteReview(entityId);
        }
        else
        {
            throw new InvalidOperationException("The type of the entity is not proper");
        }

        return Json(new { Success = true, Status = status });

    }
    catch (Exception ex)
    {

        return Json(new { Success = false, Message = ex.Message });
    }
}

然后你以与成功通话相同的方式处理它。您只需检查json响应的Success属性。然后在错误回调中处理意外错误。

答案 1 :(得分:11)

Mattias Jakobsson的回答是正确的。但我认为将错误返回给jQuery的最佳方法是创建一个JSON并发送状态为500.但是,当我这样做并尝试使用IIS 7部署我的MVC网站时,我发现它正在返回我的自定义页面而不是消息。

代码是......

catch (Exception ex)
{
    Response.StatusCode = 500;
    return Json(new { error = ex.Message });
}

然后我看到this thread引导我进入web site(来自Rick Strahl)。

总的来说,我明白你需要告诉IIS不要注入自定义错误页面,所以你需要这个标志(在global.asax中或者在catch中):

  

Response.TrySkipIisCustomErrors = true;

因此,在jQuery中,代码保持不变:

$.ajax({...})
.done(function (result) {...})
.fail(function (e) { 
   console.log(e.responseJSON.error);
});

答案 2 :(得分:0)

你应该配置jquery来处理错误:

$.ajaxSetup({
    error: function(xhr) {
        alert(xhr.statusText);
    }
})