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

后端 未结 4 1505
春和景丽
春和景丽 2021-01-15 17:29

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

For example www.site.com/Home/Index, if I have the normal default route {controller}/

相关标签:
4条回答
  • 2021-01-15 17:53

    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

    0 讨论(0)
  • 2021-01-15 18:07

    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);
          }
       }
    }
    
    0 讨论(0)
  • 2021-01-15 18:12

    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?

    0 讨论(0)
  • 2021-01-15 18:15

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题