在mvc中使用MapPageRoute注册路由,如下:
routes.MapPageRoute("test", "test", "~/test.aspx"); routes.MapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 );
然后在Controller中使用RedirectToAction,转向会错误,如下代码:
public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "欢迎使用 ASP.NET MVC!"; return RedirectToAction("About"); } public ActionResult About() { return View(); } }
RedirectToAction("About");这句执行后,会重定向到test.aspx页面,为什么会这样呢?
顺序反了
routes.MapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 );
routes.MapPageRoute("test", "test", "~/test.aspx");
如果反过来,我请求http://localhost:2775/test就不会转到test.aspx页面了,我想实现请求http://localhost:2775/test时转到test.aspx页面,其他路径转向对应的Controller实现
@何时能出头: 呵呵,昨天没有注意。这个问题的原因在于MapPageRoute其实主要是给Web Forms用的,它会与MVC默认注册的路由规则有些冲突。参考这里一个讨论http://stackoverflow.com/questions/10178276/after-add-mappageroute-to-an-asp-net-mvc-project-the-site-stops-to-enter-in-hom
一个解决方案就是添加一个约束,示例代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("test", "test", "~/test.aspx", false, null, new RouteValueDictionary { { "outgoing", new MyCustomConstraint() } });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class MyCustomConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return routeDirection == RouteDirection.IncomingRequest;
}
}
}