Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc ASP.NET MVC-生成例外上下文返回正常响应_Asp.net Mvc_Asp.net Mvc 5 - Fatal编程技术网

Asp.net mvc ASP.NET MVC-生成例外上下文返回正常响应

Asp.net mvc ASP.NET MVC-生成例外上下文返回正常响应,asp.net-mvc,asp.net-mvc-5,Asp.net Mvc,Asp.net Mvc 5,我们正在开发新的MVC5 web应用程序,其中我们使用现有的API库实现某些功能 现在,这些API库抛出某些异常类型,这些异常类型需要传回客户端浏览器 我希望如何处理这些异常: 如果调用的操作返回一个视图,则将用户带到包含异常消息的页面 如果被调用的操作返回JSON字符串,则以字符串格式返回响应 我现在关心的是#2,因为控制器的“OneException”方法始终返回服务器错误,并且默认情况下ASP.NET将返回默认自定义错误,除非我按照以下方式更改web应用程序配置 <system.we

我们正在开发新的MVC5 web应用程序,其中我们使用现有的API库实现某些功能

现在,这些API库抛出某些异常类型,这些异常类型需要传回客户端浏览器

我希望如何处理这些异常:

  • 如果调用的操作返回一个视图,则将用户带到包含异常消息的页面
  • 如果被调用的操作返回JSON字符串,则以字符串格式返回响应
  • 我现在关心的是#2,因为控制器的“OneException”方法始终返回服务器错误,并且默认情况下ASP.NET将返回默认自定义错误,除非我按照以下方式更改web应用程序配置

    <system.web> 
    ...
      <customErrors mode="Off"/>
    <system.webServer>
    ...
       <httpErrors errorMode="Detailed" />
    
    
    ...
    ...
    
    我的问题是,如何从“OneException”返回JSON字符串,而不必如上所示更改web配置?(即,提升ExceptionContext以返回常规JSON响应字符串)

    短暂性脑缺血发作

    受保护的覆盖无效OneException(ExceptionContext filterContext)
    {
    //如果已经处理了验证,我们什么也不做
    if(filterContext.ExceptionHandled)
    {
    返回;
    }
    //初始化
    var vm=new ExceptionViewModel();
    Exception ex=filterContext.Exception;
    var controllerName=filterContext.RouteData.Values[“controller”].ToString();
    var actionName=filterContext.RouteData.Values[“action”].ToString();
    //获取操作返回类型
    类型controllerType=filterContext.Controller.GetType();
    var method=controllerType.GetMethod(actionName);
    类型returnType=null;
    //若方法为null,则默认为JSONREsult
    if(方法==null)
    {
    returnType=typeof(JsonResult);
    }
    其他的
    {
    returnType=方法.returnType;
    }
    //日志异常
    vm.ErrorLogId=LogException(ex);
    //分配异常视图模型
    如果(ex是MyCustomExceptionType)
    {
    filterContext.HttpContext.Response.StatusCode=200;
    vm.ErrorMessage=filterContext.Exception.Message;
    }
    否则如果(ex为NotAuthorizedException)
    {
    //获取Http异常
    var httpEx=ex作为NotAuthorizedException;
    filterContext.HttpContext.Response.StatusCode=httpEx.GetHttpCode();
    vm.ErrorMessage=httpEx.Message;
    }
    其他的
    {
    //将状态代码设置为500,因为此异常块指示应用程序
    //发生异常
    filterContext.HttpContext.Response.StatusCode=500;
    vm.ErrorMessage=“对不起,我可能出现了故障。Toink!”;
    }
    //准备返回给客户的数据
    if(returnType.Equals(typeof(JsonResult))| | returnType.Equals(typeof(Task)))
    {
    filterContext.Result=新的JsonResult()
    {
    Data=vm.ErrorMessage,
    JsonRequestBehavior=JsonRequestBehavior.AllowGet
    };
    }
    其他的
    {
    filterContext.Result=newviewResult()
    {
    ViewName=“错误”,
    ViewData=新的ViewDataDictionary(vm)
    };
    }
    //将异常标记为已处理
    filterContext.ExceptionHandled=true;
    }
    
    protected override void OnException(ExceptionContext filterContext)
        {
            //If the exeption is already handled we do nothing
            if (filterContext.ExceptionHandled)
            {
                return;
            }
    
            // Init
            var vm = new ExceptionViewModel();
            Exception ex = filterContext.Exception;
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();
    
            // Get action return type
            Type controllerType = filterContext.Controller.GetType();
            var method = controllerType.GetMethod(actionName);
            Type returnType = null;
    
            // If method is null, default to JSONREsult
            if (method == null)
            {
                returnType = typeof(JsonResult);
            }
            else
            {
                returnType = method.ReturnType;
            }
    
            // Log exception
            vm.ErrorLogId = LogException(ex);
    
            // Assign Exception View Model
            if (ex is MyCustomExceptionType)
            {
                filterContext.HttpContext.Response.StatusCode = 200;
                vm.ErrorMessage = filterContext.Exception.Message;
            }
            else if (ex is NotAuthorizedException)
            {
                // Get Http exception
                var httpEx = ex as NotAuthorizedException;
                filterContext.HttpContext.Response.StatusCode = httpEx.GetHttpCode();
                vm.ErrorMessage = httpEx.Message;
            }
            else
            {
                // Set status code to 500 since this exception block indicates an application
                // exception occurred
                filterContext.HttpContext.Response.StatusCode = 500;
                vm.ErrorMessage = "Sorry, I may have malfunctioned. Toink!";
            }
    
            // Prepare data to return back to client
            if (returnType.Equals(typeof(JsonResult)) || returnType.Equals(typeof(Task<JsonResult>)))
            {
                filterContext.Result = new JsonResult()
                {
                    Data = vm.ErrorMessage,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                filterContext.Result = new ViewResult()
                {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary(vm)
                };
            }
    
            // Mark exception as a handled
            filterContext.ExceptionHandled = true;
        }