我正在尝试在此示例中使用string
在URL中传递queryString
参数的简单示例。首先,我添加了一个新的MapRoute
到RouteConfig.cs
文件
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "app",
url: "{controller}/{action}/{name}"
);
在Contoller中我有
public class AppController : Controller
{
public string Index(string name)
{
return HttpUtility.HtmlEncode("Hello " + name );
}
}
但视图未显示字符串参数。例如这样的URL
http://localhost:59013/App/Index/Ali
仅返回Hello
!
你能告诉我为什么会这样吗?
更新
routes.MapRoute(
name: "app",
url: "{controller}/{action}/{name}",
defaults: new {action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
答案 0 :(得分:2)
首先,您需要更改已注册路线的顺序,以便默认为最后一个。
其次,您的app
路由模式错误,并且始终与默认路由冲突。您最好将其模式更改为
url: "App/Index/{name}"
或许更友好的
url: "App/{name}"
两者都有
defaults: new { controller = "App", action = "Index" }
这样你的路线就像:
routes.MapRoute(
name: "app",
url: "App/{name}",
defaults: new { controller = "App", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
请参阅MSDN