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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2378023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:22:01  来源:igfitidea点击:

How to return error from ASP.NET MVC action

jqueryasp.netajaxasp.net-mvc

提问by Mohan Gundlapalli

I am using ASP.NET MVC for developing a web site. I am using jquery for AJAX functionality. In the action methods, I want to return some error to signal that the input is not correct or that the action could not be performed. In such error cases, I expect the jquery ajax error handler to be called and I can take appropriate action in there. I have not found a way how to do this. Following is my action method.

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

In error cases, what should I be sending from an Action in order to get the jquery error handler triggered?

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

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");
        }
    }

回答by Mattias Jakobsson

Your ajax error handler will be called when the action doesn't return a expected status code. It will, for example, fire if the action wasn't found or if you throw a exception that you don't handle. In your case it will be called if you don't catch the error in your action (as the action will return a 500 status code).

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

I would, however, not do it in this way as this is probably a expected error. I would rather return json both when you succeed and when you have a error. Then you can indicate if it is a successful call or not. Something like this:

但是,我不会这样做,因为这可能是预期错误。我宁愿在成功和出错时都返回 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 });
    }
}

Then you handle it in the same way as a successful call. You just check the Success property of your json response. Then you handle unexpected errors in the error callback.

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

回答by Adriano Galesso Alves

Mattias Jakobsson's answer is right. But I think the best way to return the error to the jQuery is creating a JSON and sending it with status 500. However, when I did it and tried to deploy my MVC website using IIS 7 I figured out that it was returning me the custom page instead of the message.

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

The code was...

代码是...

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

But then I saw this threadthat led me to this web site(from Rick Strahl).

但后来我看到了这条线索,将我带到了这个网站(来自 Rick Strahl)。

Overall, I understood that you need to say to IIS to not inject the custom error page, so you need this flag (in the global.asax or into the catch):

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

Response.TrySkipIisCustomErrors = true;

Response.TrySkipIisCustomErrors = true;

So, in jQuery the code keeps the same:

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

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

回答by ldp615

you shoud config jquery to handle error:

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

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