2

我正在将 Asp.net MVC 项目作为一个单页应用程序来处理错误。
我想将json数据从Application_Error方法返回global.asax到UI并通过jQuery显示或调用控制器并返回partialView。
我不想刷新页面或将其重定向到错误页面。

4

2 回答 2

2

这是要走的路

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();

    // if the error is NOT http error, then stop handling it.
    if (!(exception is HttpException httpException))
        return;

    if (new HttpRequestWrapper(Request).IsAjaxRequest())
    {
        Response.Clear();
        Response.TrySkipIisCustomErrors = true;
        Server.ClearError();

        Response.ContentType = "application/json";
        Response.StatusCode = 400;
        JsonResult json = new JsonResult
        {
            Data = exception.Message
        };

        json.ExecuteResult(new ControllerContext(Request.RequestContext, new BaseController()));
    }
}
于 2017-11-29T08:21:05.493 回答
1
//Write This code into your global.asax file

    protected void Application_Error(Object sender, EventArgs e)
            {
            var ex = Server.GetLastError();
                //We check if we have an AJAX request and return JSON in this case
                if (IsAjaxRequest())
                {
                    Response.Write(JsonConvert.SerializeObject(new
                            {
                                error = true,
                                message = "Exception: " + ex.Message
                            })
                        );
                }
            }


            private bool IsAjaxRequest()
            {
                //The easy way
                bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
                || ((Request.Headers != null)
                && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

                //If we are not sure that we have an AJAX request or that we have to return JSON 
                //we fall back to Reflection
                if (!isAjaxRequest)
                {
                    try
                    {
                        //The controller and action
                        string controllerName = Request.RequestContext.
                                                RouteData.Values["controller"].ToString();
                        string actionName = Request.RequestContext.
                                            RouteData.Values["action"].ToString();

                        //We create a controller instance
                        DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
                        Controller controller = controllerFactory.CreateController(
                        Request.RequestContext, controllerName) as Controller;

                        //We get the controller actions
                        ReflectedControllerDescriptor controllerDescriptor =
                        new ReflectedControllerDescriptor(controller.GetType());
                        ActionDescriptor[] controllerActions =
                        controllerDescriptor.GetCanonicalActions();

                        //We search for our action
                        foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
                        {
                            if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
                            {
                                //If the action returns JsonResult then we have an AJAX request
                                if (actionDescriptor.MethodInfo.ReturnType
                                .Equals(typeof(JsonResult)))
                                    return true;
                            }
                        }
                    }
                    catch
                    {

                    }
                }

                return isAjaxRequest;
            }


//Write this code in your ajax function in html file

<script type="text/javascript">


    $.ajax({
            url: Url
            type: 'POST',
            data: JSON.stringify(json_data),
            dataType: 'json',
            cache: false,
            contentType: 'application/json',
            success: function (data) { Successfunction(data); },
            error: function (xhr, ajaxOptions, thrownError) {
                var obj = JSON.parse(xhr.responseText);
                if (obj.error) {
                    show_errorMsg(obj.message);
                }
            }
        });

</script>
于 2014-01-23T10:06:28.690 回答