Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果存在,我如何使用第二个RoutedData值_C#_Asp.net_Routing_Url Routing_Query String - Fatal编程技术网

C# 如果存在,我如何使用第二个RoutedData值

C# 如果存在,我如何使用第二个RoutedData值,c#,asp.net,routing,url-routing,query-string,C#,Asp.net,Routing,Url Routing,Query String,我正在使用asp.net路由,其中一个变量没有问题,但我想使用两个变量,第二个变量不是必须的。可能是,也可能不是 要使用路由: products/{a}/{id} services/{b}/{id} 在这种情况下,我必须输入“a”变量和“id”变量才能访问url。但是如果没有{id}变量,我想打开url,比如: products/{a} services/{b} 如果在路由中从url中删除{id},则上面的url工作正常 我尝试添加{*id}并打开,但在打开页面时出现冲突。我找到了一个使用{

我正在使用asp.net路由,其中一个变量没有问题,但我想使用两个变量,第二个变量不是必须的。可能是,也可能不是

要使用路由:

products/{a}/{id}
services/{b}/{id}
在这种情况下,我必须输入“a”变量和“id”变量才能访问url。但是如果没有{id}变量,我想打开url,比如:

products/{a}
services/{b}
如果在路由中从url中删除{id},则上面的url工作正常

我尝试添加{*id}并打开,但在打开页面时出现冲突。我找到了一个使用{id?}的解决方案,但导致了路由错误。有什么建议吗

我的解决方案:

我添加了一条新的路线来解决这个问题。这不是最好的,但很有效。如果您有相同路线的更好解决方案,请与我们分享

routes.MapPageRoute("Products", "products/{a}", "~/products.aspx");
routes.MapPageRoute("Services", "services/{b}", "~/services.aspx");
routes.MapPageRoute("Productsid", "products/{a}/{id}", "~/products.aspx");
routes.MapPageRoute("Servicesid", "services/{b}/{id}", "~/services.aspx");

您可以通过添加规则使{id}参数成为可选参数:

    routes.MapPageRoute(
       routeName: "Products",
       routeUrl: "products/{a}/{id}",
       physicalFile: "~/products.aspx",
       checkPhysicalUrlAccess: true,
       defaults: new RouteValueDictionary(new {
       id = UrlParameter.Optional,
    });

以下是可以帮助您的更多人了解您的想法的方法

添加{id?}时会引发什么错误?您正在使用Asp.Net Web API/Asp.Net MVC应用程序吗?这是一个Asp.Net Web表单项目。它说“名为‘mainpage’的路由已经在路由集合中。路由名称必须是唯一的。”当我删除{id?}时,一切正常。我正在使用MapPageRoute进行路由,是否需要使用MapRoute进行更改?