【问题标题】:Redirecting when an argument Exception occurs发生参数异常时重定向
【发布时间】:2016-03-23 12:47:49
【问题描述】:

在我的操作方法中,我使用了 try - catch 块。该方法需要一个整数参数,并且在传递空值时显示服务器错误页面。但我希望它被重定向到自定义错误页面。

[HandleError(ExceptionType = typeof(ArgumentException), View = "~/Views/SetValues/Error")]
public ActionResult Index(int id)
{
        //if(id==null)
        //{
        //    ViewBag.Error = "A null parameters passed to the function";
        //    return View("Error");
        //}
        try
        {
             .........
        }
        catch (Exception e)
        {
            ViewBag.Error = e.Message;
            return View("Error");
        }
} 

try catch 块没有被执行,因为传递了一个空参数。 if 语句也不起作用,因为检查总是失败。

是否可以通过不将参数设置为可空来解决?

我希望它重定向到我的自定义错误页面,而不是我的函数重定向到服务器错误页面。

【问题讨论】:

    标签: c# asp.net-mvc exception


    【解决方案1】:

    不确定,但试试过滤属性:

    public class IdRequiredAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            object parameter = null;
            filterContext.ActionParameters.TryGetValue("id", out parameter);
            var id = parameter as int?;
    
            if (id == null)
            {
                var urlHelper = new UrlHelper(filterContext.Controller.ControllerContext.RequestContext);
    
                var url = urlHelper.Action("ErrorAction", "ControllerName");
    
                filterContext.Result = new RedirectResult(url);
            }
        }
    }
    
    ...
    
    [IdRequiredAttribute]
    public ActionResult Index(int id)
    {
        //...
    }
    

    【讨论】:

    • 我删除了我的评论,因为它不再有效。那么有必要在我需要执行此检查的所有功能中编写它吗?
    • 重定向有效。但它不会返回我的视图。但我应该能够修复它。
    【解决方案2】:

    正确的解决方法是使参数为可空并检查

    [HandleError(ExceptionType = typeof(ArgumentException), View = "~/Views/SetValues/Error")]
    public ActionResult Index(int? id)
    {
            if(id==null)
            {
                ViewBag.Error = "A null parameters passed to the function";
                return View("Error");
            }
            try
            {
                 .........
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
                return View("Error");
            }
    } 
    

    另外一点,如果你不让它可以为空,那么 MVC 框架将无法到达你的 Index 操作,因为它无法解析路由。一种解决方法是将参数设为字符串并检查是否可以从中解析整数值以继续进行。

    【讨论】:

    • 但是我已经在问题中提到了关于不使参数可为空的解决方法。感谢您的回答。
    【解决方案3】:

    为了显示自定义错误页面,请执行以下操作 -->在Web.config文件中添加这个

    <customErrors mode="On" defaultRedirect="~/Controller/Action" />
    

    然后使用这个控制器和视图来显示你的错误页面。

    注意:- 这可用于未捕获的异常并避免黄页(错误页面)。但是,您也应该使用错误日志记录来获取详细信息。 Check this link for error logging

    使用它你也可以处理 404 和其他异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 2011-08-07
      • 2012-05-01
      • 1970-01-01
      • 2012-09-01
      • 2012-12-13
      • 1970-01-01
      相关资源
      最近更新 更多