简体   繁体   English

C#3.5 MVC2路由跳过可选参数

[英]C#3.5 MVC2 routing skip optional param

Here I have: 我在这里:

routes.MapRoute(
    "test", // Route name
    "DataWarehouse/Distribution/{category}/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional } 
);

Category and serialNo are both optional params. Category和serialNo都是可选参数。 When the routing is like: DataWarehouse/Distribution/123 , it always treat 123 as the value for category. 当路由类似: DataWarehouse/Distribution/123 ,它将始终将123视为类别的值。

My question is how I can make it to know the 1st param could be either category or serialNo, ie DataWarehouse/Distribution/{category} and DataWarehouse/Distribution/{serialNo} . 我的问题是,如何让我知道第一个参数可以是category或serialNo,即DataWarehouse/Distribution/{category}DataWarehouse/Distribution/{serialNo}

DataWarehouse/Distribution/{category}/{serialNo}

Only the last parameter can be optional. 只有最后一个参数可以是可选的。 In this example category cannot be optional for obvious reasons. 在此示例中,出于明显的原因,类别不能是可选的。

If you know what your parameters will look like you can add a route constraint to differentiate both routes 如果您知道参数的外观,则可以添加一条路线约束以区分两条路线

Ex if your serial are 1234-1234-1234 and your category are not like this: 例如,如果您的序列号是1234-1234-1234并且您的类别不是这样的:

routes.MapRoute(
    "serialonly", // Route name
    "DataWarehouse/Distribution/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional },
    new{serialNo = @"\d{4}-\d{4}-\d{4}"} 
);

routes.MapRoute(
    "test", // Route name
    "DataWarehouse/Distribution/{category}/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional },
    ,
    new{serialNo = @"\d{4}-\d{4}-\d{4}"}  
);

I had a similar problem, i was trying to route based on data ( {year}/{month}/{day} ) where month or day could be optional. 我有一个类似的问题,我试图根据数据( {year}/{month}/{day} )进行路由,其中monthday可能是可选的。 What I found was that I couldn't do it with a single route. 我发现我无法用一条路线做到这一点。 So I solved it by using 3 routes, from generic to specific (year, year and month, year and month and day). 因此,我通过使用从通用到特定(年,年和月,年,月和日)的3条路线解决了该问题。 I am not completely pleased with it, but it works. 我对此并不完全满意,但是它可以工作。

So provided that you are looking for DataWarehouse/Distribution/{category} and DataWarehouse/Distribution/{category}/{serialNo} routes, i think this would work for you. 因此,如果您正在寻找DataWarehouse/Distribution/{category}DataWarehouse/Distribution/{category}/{serialNo}路由,我认为这对您DataWarehouse/Distribution/{category}/{serialNo}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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