Display View in folder without Controller or Action in ASP.net MVC

瘦欲@ 提交于 2019-12-01 10:45:32

For missing actions you can override HandleUnknownAction.

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);
      }
   }
}

I came across the same issue recently while developing AJAX web applications where most of the pages don't actually need a controller (all the data is returned via Web API calls).

It seemed inefficient to have dozens of controllers all with a single action returning the view so I developed the ControllerLess plugin which includes a default view controller behind the scenes with a single action.

If you create a controller for your view, then MVC will use that. However, if you create a view without a controller, the request is re-routed via the default plugin controller.

It works with C# and VB.NET and us available at https://www.nuget.org/packages/ControllerLess

The source code is also available on GitHub at https://github.com/brentj73/ControllerLess

You cannot and shouldn't the way you want. Views cannot be addressed by design (in the web.config in the /views folder theres an HttpNotFoundHandler mapped to * to ensure this)

With that said, what you want here is not really standard so why do you want to do this, maybe we can come up with a better suggestion based on the reason behind this?

Never tried this, but here's a thought. You can setup constraints for the routes, and thus you should be able to create a route matching "{folder}/{file}" where you constraint them to valid values (you can google this, or seach her on SO), and set it to run on a FileController (arbitrary name) with some default action. Then, in that action, simply return the desired view. Something like:

public class FileController : Controller {
    public ActionResult Default(string folder, string file) {
        return View(folder + "/" + file);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!