ASP MVC默认路由不适用于根站点url

时间:2014-05-29 21:16:53

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

我无法让ASP.net MVC为根站点网址http://mysite:8080/提供默认控制器索引视图。我得到的全部是404 The resource cannot be found。如果我在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 }
);

1 个答案:

答案 0 :(得分:0)

以下是此问题的解决方案。令人失望的是,默认路由的默认值不适用于根站点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);
    }
}