【发布时间】:2014-02-11 17:45:30
【问题描述】:
我正在构建一个博客系统,但我似乎无法让 ASP.NET MVC 了解我的路线。
我需要的路由是 /blogs/student/firstname-lastname 所以 /blogs/student/john-doe,它路由到博客区域,学生控制器的索引操作,它采用字符串名称参数。
这是我的路线
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action="Index"}
);
我的控制器操作
public ActionResult Index(string name)
{
string[] nameparts = name.Split(new char[]{'-'});
string firstName = nameparts[0];
string lastName = nameparts[1];
if (nameparts.Length == 2 && name != null)
{
// load students blog from database
}
return RedirectToAction("Index", "Index", new { area = "Blogs" });
}
但它似乎无法解决...它与 /blogs/student/?name=firstname-lastname 一起工作正常,但不使用我想要的路线,即 /blogs/student/firstname-lastname。任何有关如何解决此问题的建议将不胜感激。
我的路由配置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "StudentBlogs",
url: "blogs/student/{name}",
defaults: new { controller = "Student", action = "Index"},
constraints: new { name = @"[a-zA-Z-]+" },
namespaces: new string[] { "IAUCollege.Areas.Blogs.Controllers" }
);
routes.MapRoute(
name: "Sitemap",
url :"sitemap.xml",
defaults: new { controller = "XmlSiteMap", action = "Index", page = 0}
);
//CmsRoute is moved to Gloabal.asax
// campus maps route
routes.MapRoute(
name: "CampusMaps",
url: "locations/campusmaps",
defaults: new { controller = "CampusMaps", action = "Index", id = UrlParameter.Optional }
);
// core route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// error routes
routes.MapRoute(
name: "Error",
url: "Error/{status}",
defaults: new { controller = "Error", action = "Error404", status = UrlParameter.Optional }
);
// Add our route registration for MvcSiteMapProvider sitemaps
MvcSiteMapProvider.Web.Mvc.XmlSiteMapController.RegisterRoutes(routes);
}
}
【问题讨论】:
-
它实际上匹配哪条路线?您只向我们展示了一个您的映射路线。
-
在尝试 /blogs/student/firstname-lastname 时会抛出 404,但如果我使用 /blogs/student/?name=firstname-lastname 它会解析 /blogs/student/ 控制器的索引操作,它有一个字符串参数名称。
标签: c# asp.net asp.net-mvc asp.net-mvc-4 routes