显示视图中的文件夹没有控制或操作ASP.net MVC视图、文件夹、操作、MVC

2023-09-06 14:06:51 作者:像温柔野兽

我想在文件夹中显示的视图,如果没有控制器/动作相匹配。

I would like to display the view in the folder if no controller/action matches.

例如www.site.com/Home/Index,如果我有正常默认路由{控制器} / {行动} / {ID}然后我需要方法索引一个HomeController的。 而且还有一个文件夹中查看文件夹,名为家庭和文件Index.cshtml

For example www.site.com/Home/Index, if I have the normal default route {controller}/{action}/{id} then I need a HomeController with method Index. And there is a folder in Views folder called Home and the file Index.cshtml

如果我尝试www.site.com/About/Index我需要创建AboutController和方法的索引。 但我刚才的文件夹,关于和文件Index.cshtml。

If i try www.site.com/About/Index i need to create the AboutController and the method index. But I have just the folder About and file Index.cshtml.

我想,如果没有缺省路由匹配,但我有一个文件夹,并在浏览文件夹中的文件相匹配的百通说:{}控制器是文件夹{}行动是视图;那么视图。

I would like that if the default route does not match but I have a Folder and a File in the Views folder that match the patern: {controller} is the folder {action} is the view; then that view is displayed.

我怎么能achive呢?

How could I achive that?

推荐答案

有关失踪的行动,你可以覆盖的 HandleUnknownAction 。

For missing actions you can override HandleUnknownAction.

有关失踪控制器,可以实现自定义 DefaultControllerFactory 并覆盖GetControllerInstance像这样的东西:

For missing controllers you can implement a custom DefaultControllerFactory and override GetControllerInstance with something like this:

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {

   if (controllerType == null)
      return new DumbController();

   return base.GetControllerInstance(requestContext, controllerType);
}

class DumbController : Controller {

   protected override void HandleUnknownAction(string actionName) {

      try {
         View(actionName).ExecuteResult(this.ControllerContext);
      } catch (Exception ex) {
         throw new HttpException(404, "Not Found", ex);
      }
   }
}