2012-10-29 36 views
2

我正在将Asp.net MVC项目作为单页应用程序进行错误处理。
我想从Application_Error方法global.asax中将json数据返回给UI,并通过jQuery显示它或调用控制器并返回partialView。
我不想刷新页面或将其重定向到错误页面。如何从global.asax中的App_Error以json格式返回异常数据?

+0

使用操作,而不是过滤器的方式。 – asawyer

+0

可能的重复[需要一些自定义ASP.NET MVC IExceptionFilter的帮助](http://stackoverflow.com/questions/1419414/need-some-help-with-a-custom-asp-net-mvc-iexceptionfilter) – asawyer

+1

看看这个问题:http://stackoverflow.com/questions/4707755/asp-net-mvc-ajax-error-handling – webdeveloper

回答

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> 
0

这里是去

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