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

Moh*_*lli 16 asp.net ajax asp.net-mvc jquery

我正在使用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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我没有投票,但我不同意.(抱歉,@ Mattias).这将导致JavaScript"成功"回调触发.我们总是希望在服务器上出现错误时触发错误回调.这违反了语法.在语法上,我们想要返回500系列错误. (3认同)

Adr*_*ves 12

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

代码是......

catch (Exception ex)
{
    Response.StatusCode = 500;
    return Json(new { error = ex.Message });
}
Run Code Online (Sandbox Code Playgroud)

但后来我看到了这个线索让我进入了这个网站(来自Rick Strahl).

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

Response.TrySkipIisCustomErrors = true;

所以,在jQuery中代码保持不变:

$.ajax({...})
.done(function (result) {...})
.fail(function (e) { 
   console.log(e.responseJSON.error);
});
Run Code Online (Sandbox Code Playgroud)

  • 这是一个出色而完整的答案。您展示了控制器 ** 和** 相应 AJAX 调用的示例。感谢您抽出宝贵的时间。 (2认同)