开发者

Why doesnt this MVC routing work?

开发者 https://www.devze.com 2023-04-12 20:00 出处:网络
//standard routing routes.MapRoute( \"Default\", // Route name \"{controller}/{action}/{id}\", new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }
        //standard routing
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        );

        //the custom route I added
        routes.Add(
           new Route("Fish/Image",

               new ImageHandlerRouteHandler()
           )
        );
开发者_JAVA技巧

I thought this would use my ImageHandlerRouteHandler but all I get at Fish/Image is a 404.


Add the route before the default route.

routes.Add(
           new Route("Fish/Image",

               new ImageHandlerRouteHandler()
           )
        );

//standard routing
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        );

The request is mapped to the first matching route in routes table. Since default route have no restrictions, it gets called before your custom route.


When you have the Fish/Image route before the default route, the problem you will have in MVC building links is that the Fish/Image route appears to satisfy ALL requests. In order to have this route work, change it as follows:

routes.Add(
    "FishImage",
    new Route(
        "{controller}/Image", 
        new RouteValueDictionary(new { controller = "Fish" }),
        new RouteValueDictionary(new { controller = @"^(?!fish).+"  }),
        null,
        new ImageHandlerRouteHandler() 
    ) 
);

This changes the route, so that on the link building side, your other links will fail this route. Currently, MVC sees that it can build any link to match this route, so it does. With the constrained route, MVC will now see that other links will fail this route.


The order that routes appear are important. Add your route first and left the Default as a fall back.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号