简体   繁体   中英

Configuring URL Routes in an asp.net hybrid (web forms and mvc) app

I have an app that others have worked on that was originally a Web.forms app with multiple parts and is being converted to MVC. There are two parts that have gone to MVC and one works fine but the other I am having routing issues.

The route appears in .cshtml as:

<a href="@Url.RouteUrl("TableDetails", new { id=testTable.theId })@Request.Url.Query">Test Table</a>

The project is web forms with a folder called Areas > TableProject > Controllers and other folders related to the mvc project. In controllers is a HomeController.cs that has:

[HttpGet]
[Route("{id:int}/{seId:int?}", Name = "TableDetails")]
public ActionResult TableDetails(int id, int? seId)
{
    // code
}

The route file is as such:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.RouteExistingFiles = false;
        routes.IgnoreRoute("anotherproject/{*pathInfo}");

        routes.MapPageRoute(
            "WebFormDefault",
            string.Empty,
            "~/index.aspx");

        routes.MapRoute(
            "MvcDefault",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }         

I cannot get the table project to work as the TableDetails route cannot be found. The other MVC project works fine.

The error is:

A route named 'TableDetails' could not be found in the route collection. Parameter name: name

You are missing the method call to register attribute routing, MapMvcAttributeRoutes . That means that none of your [Route] attributes are being registered.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.RouteExistingFiles = false;
    routes.IgnoreRoute("anotherproject/{*pathInfo}");

    // Register [Route] attributes
    routes.MapMvcAttributeRoutes();

    routes.MapPageRoute(
        "WebFormDefault",
        string.Empty,
        "~/index.aspx");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

In addition, the MvcDefault route is blocking every call to the Default route, making Default an unreachable execution path. See Why map special routes first before common routes in asp.net mvc? for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM