Is there a way to add a default view and a default controller in ASP.NET MVC 2?

What I really would like to do is redefine the conventions to do the following:

For controllers and their respective actions:

If a URL request is given and there is no controller with the action provided, perform some of the "default" functions that I will set for myself in the application. I would have thought that this could be achieved using Func <>, but I'm not sure where to turn it on.

For views:

If the controller action requests a view, and there is no view that matches the request that requests the controller action, return that view by default.

Is this something possible, and if so, where should I delve into to find out more about how to do this? Or is it really a simple thing?

EDIT

Here is an example of what I'm trying to achieve.

I have a very simplified view, something similar to this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 

Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%: Html.LabelForModel() %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <%: Html.EditorForModel() %>

</asp:Content>

So, let's say I have a Customer class, and the controller action does something with the Customer object, and then does

return View(someCustomer);

The problem here is that I did not define any kind for processing the Client. In this case, I want my view mechanism (or something not to respond), saying: "Ok, there is no view that processes Clients directly, instead I use the default view."

+3
source share
4 answers

You are requesting several different components.

"DefaultController" " ".

, factory:

protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
    try
    {
        return base.GetControllerInstance(requestContext, controllerType);
    }

    catch (HttpException ex)
    {
        int httpCode = ex.GetHttpCode();
        if(httpCode == (int)HttpStatusCode.NotFound)
        {
            IController controller = new DefaultController();
            ((DefaultController)controller).DefaultAction();
            return controller;
        }
        else
        {
            throw ex;
        }
    }
}

factory Global.asax.

, , , HandleUnknownAction, :

public class BaseController : Controller
{
    protected override void HandleUnknownAction(string actionName)
    {
        RouteData.Values["action"] = "DefaultAction";

        if ( this.ActionInvoker.InvokeAction(this.ControllerContext, "DefaultAction"))
               return;

        base.HandleUnknownAction(actionName);
    }
}

, " ", :

public class MyWebFormViewEngine : WebFormViewEngine
{
    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        ViewEngineResult result = null;

        result = base.FindView(controllerContext, viewName, masterName, useCache);

        if (result == null || result.View == null)
           result = base.FindView(controllerContext, "Default", masterName, useCache);

        return result;
    }
}

Global.asax:

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new MyWebFormViewEngine());

    RegisterRoutes(RouteTable.Routes);
// etc
}

, ...

+1

/ ?

, ? /, ?

routes.MapRoute(
    "Root",
    "",
    new { controller = "Home", action = "Index" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    // constraints for certain controllers (add actions if needed as well)
    new { controller = "Home|ControllerOne|ControllerTwo|..."}
);

// catch any request route and handle by the same controller/action
routes.MapRoute(
    "NonExisting",
    "{path*}",
    new { controller = "Default", action = "Any" }
);

, . , - , , .

( )

, , , aspx .

, Views/{0}/{1}.aspx. , Views/General/Default.aspx, . Whe , , , , .

+2

. - , 404 ( ).

protected void Application_Error(object sender, EventArgs e) {
    HttpException httpException = Server.GetLastError() as HttpException;
    if (httpException != null) {
        switch (httpException.GetHttpCode()) {
            case 404:
                //we couldn't find the controller or action

                //setup a new route to your default controller assigned
                //to handle unknown routes
                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "YourDefault");

                //create an instance of your controller and execute it
                IController yourDefaultController = new YourDefaultController();
                yourDefaultController.Execute(new RequestContext(
                        new HttpContextWrapper(Context), routeData));
                break;
        }
    }

}
0

, factory. , google (touch wood).

You should consider creating a custom viewer (or just expanding the default viewer) to look for different files by default.

HTHS,
Charles

0
source

Source: https://habr.com/ru/post/1767199/


All Articles