如果您加载Durandal SPA模板并尝试导航到伪造的URL(通过在URL上添加“ assdf”之类的东西),则该URL将得到维护,并且不会提供任何错误。如何进行更改,以使无效的URL给用户一个错误页面?我认为出错比让用户怀疑他们的URL是否有效更好。
最佳答案
您是否查看过handleInvalidRoute:
http://durandaljs.com/documentation/Router/
例如,在“热毛巾”中,它用于向用户显示错误的吐司。
编辑:例如,我创建了一个基本的错误视图,然后将其添加到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:如果您也担心普通的url(不是将由durandal \ sammy处理的哈希URL),则需要在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?
关于javascript - 如果DurandalJS URL无效,则不会重置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16005014/