如果您加载Durandal SPA模板并尝试导航到虚假URL(通过向URL添加类似“assdf”的内容),则会保留网址并且不会提供错误。如何更改以便无效的URL为用户提供错误页面?我认为错误比让用户想知道他们的URL是否有效更好。
答案 0 :(得分:2)
你看过handleInvalidRoute:
http://durandaljs.com/documentation/Router/
例如,在Hot Towel中,它用于向用户显示错误吐司。
编辑:例如,我创建了一个基本的错误视图,然后将其添加到main.js并且它似乎有效,但我认为我更喜欢使用咆哮类型方法向Hot Towel中的用户显示错误。
app.start().then(function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
// ** ADDED **
router.handleInvalidRoute = function (route, params) {
router.navigateTo('#/error');
};
//configure routing
router.useConvention();
router.mapNav('welcome');
router.mapNav('flickr');
// ** ADDED **
router.mapRoute('error', 'viewmodels/error', 'error', false);
app.adaptToDevice();
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
});
EDIT2:如果你也担心正常的网址(不是由durandal \ sammy处理的哈希),那么你需要在durandal之外处理它。即你可以在global.asax中添加如下内容:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
var httpException = exception as HttpException;
if(httpException != null) //It's an Http Exception, Let's handle it.
{
switch (httpException.GetHttpCode())
{
case 404:
// Page not found.
Response.Redirect("~/#/error");
break;
}
}
}
请点击此处查看更完整的方法:How can I properly handle 404 in ASP.NET MVC?