且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC有一个强制参数和一个可选参数路由?

更新时间:2022-10-17 18:25:56

我假设你创建了新的途径,离开了默认的一个是与你的差不多。你应该知道的路由集合运行到找到第一个匹配的路由。所以,如果你已经离开了默认的:

  routes.MapRoute(
            默认,//路线名称
            {控制器} / {行动} / {ID},// URL带参数
            新{控制器=家,行动=索引,ID = UrlParameter.Optional} //参数默认
        );

您的路线上方,然后它会匹配请求的http:// [MYSERVER] /我的/ MyAction / Test1的并调用 MyController.MyAction ,并设置文本1到参数名为 ID 。这是因为这个动作是不是宣告一个命名的失败 ID

您需要做的是将您的路线首先在路由表,使之更加具体的话,现在是:

  routes.MapRoute(
            路线,
            我/ {行动} / {参数1} / {参数2},
            新
            {
                控制器=我,
                行动=MyAction,
                参数1 =,
                参数2 =
            });

这将迫使所有的流量路由的低谷我的来搭配这条路线。

I've been working on a large MVC application over the past month or so, but this is the first time I've ever needed to define a custom route handler, and I'm running into some problems. Basically I have two parameters to pass. The first one is required and the second one is optional.

I'm following this answer here.

Here is my custom route:

routes.MapRoute(
    "MyRoute",
    "{controller}/{action}/{param1}/{param2}",
    new { 
        controller = "MyController", 
        action = "MyAction", 
        param1 = "", 
        param2 = "" // I have also tried "UrlParameter.Optional" here.
    }
);

And my action method signature:

public ActionResult MyAction(string param1, string param2)

If I try the URL http://[myserver]/MyController/MyAction/Test1/Test2 then it works like I expect it to, with param1 = "Test1" and param2 = "Test2"

If I try the URL http://[myserver]/MyController/MyAction/Test1 then both parameters are null.

Hopefully somebody can tell me what I'm doing wrong here, because I'm lost.

I assume that you created new route and left the default one that is very similar to yours. You should be aware that collection of routes is traversed to find first matching route. So if you have left the default one:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

above your route then it will match request to http://[myserver]/My/MyAction/Test1 and call MyController.MyAction and set "Text1" to parameter named id. Which will fail because this action is not declaring one named id.

What you need to do is to move your route as first in routes list and make it more specific then it is now:

routes.MapRoute(
            "Route",
            "My/{action}/{param1}/{param2}",
            new
            {
                controller = "My",
                action = "MyAction",
                param1 = "",
                param2 = ""
            });

This will force all traffic routed trough My to match this route.