如何防止System.NotSupportedException:不支持给定路径的格式

时间:2011-05-17 06:05:27

标签: asp.net-mvc-3

当使用坏网址并且接受所有字符时 - 使用.config键的注册表(有关详细信息,请参阅其他“重复”帖子),asp.net mvc崩溃。

防止/处理异常的最佳截取点是什么?

示例网址

http://www.local.com/some/url/pagehttp://www.local.com/some/url/page
http://www.local.com/some/url/page:12

示例异常

System.NotSupportedException 不支持给定路径的格式。

at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath) 
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath) 
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList) 
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList) 
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path) 
at System.Web.HttpRequest.MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, Boolean allowCrossAppMapping) 
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) 
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) 
at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext) 
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) 
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() 
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) 
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) 
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) 
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)

1 个答案:

答案 0 :(得分:1)

固定。

将此添加到您的Application_Start:

filters.Add(new MyHandleErrorAttribute { Order = 1, ExceptionType = typeof(NotSupportedException) });

将此课程纳入您的项目:

public class MyHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute {
  public override void OnException(ExceptionContext filterContext) {
     if (filterContext.IsChildAction || filterContext.ExceptionHandled || !ExceptionType.IsInstanceOfType(exception) || exception.Message != "The given path's format is not supported." ) 
       return;
  }

  base.OnException(filterContext);
  filterContext.HttpContext.Response.StatusCode = 404;
}

然后你可以处理Application_Error中的404。