【问题标题】:ASP MVC default route is not applying for root site urlASP MVC 默认路由不申请根站点 url
【发布时间】:2014-06-02 01:57:21
【问题描述】:

我无法让 ASP.net MVC 为根站点 url http://mysite:8080/ 提供默认控制器索引视图。我得到的只是带有The resource cannot be found 的404。如果我在 url 中指定完整的路由路径,它可以正常工作:http://mysite:8080/Default/Index,但是,即使用户没有指定路由路径,我也希望应用默认路由。看来这应该只是解决问题。这是一个来自 VS2013 MVC 4 模板的新项目。

我已经尝试了下面的两种路由映射,但似乎都不起作用。如何实现?

routes.MapRoute(
    "Root",
    "",
    new { controller = "DefaultController", action = "Index" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "DefaultController", action = "Index", id = UrlParameter.Optional }
);

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-mvc-routing


    【解决方案1】:

    这是解决此问题的方法。令人失望的是,默认路由的默认值不适用于根站点 url。

    routes.Add(new Route("", new SiteRootRouteHandler("~/Default/Index")));
    
    public class SiteRootRouteHandler : IRouteHandler
    {
        private readonly string _redirectUrl;
        public SiteRootRouteHandler(string redirectUrl)
        {
            _redirectUrl = redirectUrl;
        }
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new SiteRootHandler(_redirectUrl);
        }
    }
    
    public class SiteRootHandler: IHttpHandler
    {
        private readonly string _redirectUrl;
        public SiteRootHandler(string redirectUrl)
        {
            _redirectUrl = redirectUrl;
        }
        public bool IsReusable
        {
            get { return true; }
        }
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.RedirectPermanent(_redirectUrl);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多