您可以在 global.asax 中创建两条路线。像这样的东西
routes.MapRoute("", "posts/{url}", new { controller = "Home", action = "Posts" });
routes.MapRoute("", "{url}", new { controller = "Home", action = "Posts" });
他们都指向HomeController
和动作Posts
public ActionResult Posts(string url)
{
}
处理您应该考虑扩展RouteBase类的每个 url
应该做这样的事情
public class CustomRouting : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath;
//Handle the request
//Compile the RouteData with your data
result = new RouteData(this, new MvcRouteHandler());
result.Values.Add("controller", "MyController");
result.Values.Add("action", "MyAction");
result.Values.Add("id", MyId);
}
}
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
//I only need to handle outbound so here is ok
return null;
}
}
在您的 global.asax 中注册您的自定义路由处理程序
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new CustomRouting());
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}