我正在尝试使用默认的一个在RouteConfig.cs文件中配置自定义URL:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/id/{id}", //Custom url route
defaults: new { controller = "Product", action = "AddImages", id = UrlParameter.Optional }
);
}
当我在网址中写下以下内容时,上述工作正常:第一次路由
http://localhost:1234/Product/AddImages/id/1008
同样,以下内容也适用:第二次路由
http://localhost:1234/Product/AddImages/1008
但我想强制网址在地址栏中显示或写入网址,作为特定网页“AddImages”的第一个网址,如下所示:http://localhost:1234/Product/AddImages/id/1008
有没有办法做到这一点我的意思是保留默认路由和特定页面,第一个路由选项?
同样,我尝试从第一个URL检索QueryString,如下所示:
int id = Convert.ToInt32(Url.RequestContext.RouteData.Values["id"]); //This works for the second routing option
它说 - 输入字符串的格式不正确。我想,这是默认路由选项,因为它配置为:
url: "{controller}/{action}/{id}"
同样,是否可以从下面的url获取QueryString值或配置任何内容:
http://localhost:1234/Product/AddImages/id/1008
答案 0 :(得分:1)
在MVC的路由表中,首先定义的路由具有最高优先级。因此,您只需要确保您的特定路由优先于默认路由。只需更早地定义它。就是这样 - 正如评论中提到的那样。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/id/{id}", //Custom url route
defaults: new { controller = "Product", action = "AddImages", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
如果您只想要第一个,请尝试删除通用的
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/id/{id}", //Custom url route
defaults: new { controller = "Product", action = "AddImages", id = UrlParameter.Optional }
);
}
如果你只想要那个控制器,那就试试吧 -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default2",
url: "Product/{action}/id/{id}", //Custom url route
defaults: new { action = "AddImages", id = UrlParameter.Optional },
constraints: new { controller = "Product" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
有一种更好的方法来获取url参数。而不是
int id = Convert.ToInt32(Url.RequestContext.RouteData.Values["id"]); //
试试这个 -
int id = Convert.ToInt32(Request.Params["id"]); //
但是如果你正确定义了你的动作方法,你甚至不需要从请求中读取它。它将自动映射。