当我在网址中添加CheckInvalidPathChars()
,<
这样的无效字符时,我从>
方法中获得了自动例外。
自动检查路径,我想捕获异常,以便将用户重定向到404 error
页面。
如何捕获该异常?
相关信息:
我正在使用Umbraco 4.9.0
解决方案我发现:
我在项目的根目录中创建了文件Global.asax。此文件包含“Application_Error”方法,该方法在URL中存在非法字符时触发。
我使用以下代码编辑了此方法:
protected void Application_Error(object sender, EventArgs e)
{
Server.ClearError();
string errorTemplate = library.RenderTemplate(nodeId);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Length", errorTemplate.Length.ToString());
HttpContext.Current.Response.Write(errorTemplate);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
希望这有帮助!
答案 0 :(得分:1)
答案很简单 - 不要在网址中添加无效字符: - )
但严重的是,不要试图捕获错误,而是尝试阻止这些字符进入您的网址。如果字符是由代码生成的,则对其进行编码,或者在config/umbracoSettings.config
文件中有一个部分,您可以在其中指定要从Umbraco从页面标题创建的路径中排除的字符。
我几乎总是在默认值中添加额外的字符。这可确保在发布页面时,从URL路径中删除任何无效字符。
答案 1 :(得分:0)
我会使用try-catch块:
try
{
// code that could throw the exception - probably when you call the CheckInvalidPathChars() method
}
catch (Exception e)
{
// exception code
}
在https://stackoverflow.com/a/1177444/2402338处,您可以找到有关如何捕获特定异常的答案。