如果捕获所有路由不匹配,则显示 404 File Not Found 查看
我在 ASP.NET MVC 中设置了一个包罗万象的路由,因此我可以捕获 /this-page、/that-page 等。
当您点击某个页面时,就会调用该操作,例如 Index(string page),然后根据数据库中的值测试
page
以确定是否可以找到该页面。如果找不到,我想显示 ErrorController
中的视图 FileNotFound
,我不想重定向,因为我想将 url 保留为 < a href="http://.../page-that-isnt-found" rel="nofollow noreferrer">http://.../page-that-isnt-found,与 StackOverflow 完全相同事实上,如果你给它一个虚假的问题 - (https://stackoverflow.com/questions/zzz-aaa) 。
现在我的问题在于弄清楚代码,我已经尝试了两种方法:
[ do page db check ]
if (page == null)
return RedirectToAction("FileNotFound", "Error");
// return View("FileNotFound"); // can't opt for a controller ?
我得到的最接近的是 RedirectToAction()
,但是它当然会进行实际的重定向,并且我的 url 指向 /error不是期望的行为。我尝试过使用 return View()
但似乎我无法指定控制器,只能指定视图名称?
I have a catch-all route setup in ASP.NET MVC, so I can capture /this-page, /that-page etc.
When you hit a page the action is invoked, say Index(string page)
and then page
is tested against a value in the database to determine if the page can be found. If it can't be found, I want to display the view FileNotFound
which is in my ErrorController
, I do not want to redirect as I want to keep the url as http://.../page-that-isnt-found, exactly like StackOverflow does in fact if you give it a bogus question - (https://stackoverflow.com/questions/zzz-aaa).
Now my problem lies with figuring out the code, I have tried both:
[ do page db check ]
if (page == null)
return RedirectToAction("FileNotFound", "Error");
// return View("FileNotFound"); // can't opt for a controller ?
The closest I get is with RedirectToAction()
, however of course it does an actual redirect, and my url is pointed at /error which is not desired behaviour. I have tried using return View()
but it seems I can't specify a controller, only the view name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正确,通过返回视图,您指向要呈现的视图名称,而不是 ActionMethod。您应该能够创建一个返回的包含 404 页面内容的视图(在同一控制器的视图或共享视图中)。
希望这有帮助。
Correct, by returning a View, you are pointing to a View name to be rendered, not an ActionMethod. You should be able to create a View (either in the same controller's views or the shared views) that you return that contains your 404 page content.
Hope this helps.
您还可以使用 Server.Transfer 保留原始 url。这里有关于如何在 asp.net mvc 中实现此目的的好帖子 - 如何在 ASP.NET MVC 中模拟 Server.Transfer?
You can also use Server.Transfer to preserve the original url. There is good thread on how to make this in asp.net mvc here - How to simulate Server.Transfer in ASP.NET MVC?