HandleErrorAttribute不起作用

时间:2016-11-14 08:15:10

标签: c# asp.net-mvc

我有这堂课:

 public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

并在Global.asax方法Application_start中调用,如下所示:

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

我有这个网址:

  

本地主机:7708 /博客/索引/ 12

Index Method是:

 public virtual ActionResult Index(int code, string title)
    {
        var result = _pageService.Get(code.ToUrlDecription());
        return View(result);
    }

我想在url没有代码(12)返回404.html时。 为此我在web.config中设置了这些:

 <httpErrors errorMode="Custom">
  <remove statusCode="404" />
  <error statusCode="404" path="404.html" responseMode="File" />
  <remove statusCode="500" />
  <error statusCode="500" path="500.html" responseMode="File" />
</httpErrors>

但是当我有这个网址时:

localhost:7708/blog/Index

它的回归:

  

参数字典包含参数&#39;代码的空条目。非可空类型的System.Int32&#39;方法&#39; System.Web.Mvc.ActionResult索引(Int32,System.String)&#39;在&#39; IAS.Store.Web.Controllers.BlogController&#39;。可选参数必须是引用类型,可空类型,或者声明为可选参数。

1 个答案:

答案 0 :(得分:2)

您可能需要自定义错误属性:

    [AttributeUsage(AttributeTargets.Method)]
    public class MissingParamAttribute : HandleErrorAttribute
    {
        private string _paramName;

        public MissingParamAttribute(string paramName)
        {
            _paramName = paramName;
        }

        public override void OnException(ExceptionContext filterContext)
        {
            if(filterContext.Exception is ArgumentException)
            {
                const string pattern = @"The parameters dictionary contains a null entry for parameter '([^']+)'.+";
                var match = Regex.Match(filterContext.Exception.Message, pattern, RegexOptions.Multiline);
                if(match.Success && match.Groups[1].Value == _paramName)
                {
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 404;
                    return;
                }
            }
            base.OnException(filterContext);
        }
    }

并在Index操作上应用该自定义属性:

[MissingParam("code")]
public ActionResult Index(int code, string title)
{
    var result = _pageService.Get(code.ToUrlDescription());
    return View(result);
}