【问题标题】:asp.net-mvc's ROUTE: The resource cannot be foundasp.net-mvc ROUTE:找不到资源
【发布时间】:2012-08-17 06:51:54
【问题描述】:

我正在使用 asp.net mvc,但无法访问我的页面,出现 404 错误。

页面的网址:

localhost:2334/RawData/EiphoneNews

查看文件位置:

webroot/View/RawData/TNews/Index.cshtml

我的路线:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
           "RawData", // Route name
           "RawData/{controller}/{action}/{id}", // URL with parameters
           new { controller = "EiphoneNews", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
           new string[] { "News.Controllers.RawData" }
       );
    }




    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

我的控制器:

namespace News.Controllers.RawData
{
    public class EiphoneNewsController : AuthorizedController
    {
        //
        // GET: /EiphoneNews/
        public ActionResult Index(int pagenum = 0, int pagesize = 20, string queryString = null)
        {...}
    }
}

【问题讨论】:

  • 切换默认和 RawData MapRoutes。现在它首先检查默认值。

标签: c# asp.net .net asp.net-mvc routes


【解决方案1】:

交换 2 个路由定义:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
       "RawData", // Route name
       "RawData/{controller}/{action}/{id}", // URL with parameters
       new { controller = "EiphoneNews", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
       new string[] { "News.Controllers.RawData" }
   );


    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

}

【讨论】:

  • thx,404错误解决了,但是找不到视图文件,我的视图文件位置是:webroot/View/RawData/TNews/Index.cshtml
  • 不,你的视图必须是:~/Views/EiphoneNews/Index.cshtml
  • 我不能设置一些值让 asp.net-mvc 搜索路径吗?
  • 可以,但是为什么要违反标准约定呢?返回视图时可以指定路径:return View("~/View/RawData/TNews/Index.cshtml", someViewModel);.
  • 如果某些控制器中必须使用该视图,可以将视图放在Views\Shared中
【解决方案2】:

切换路由注册,第一个匹配的路由不是RawData的路由。由于路由是在控制器解析之前确定的,因此默认路由会导致 404 而RawData 路由不会。

您可能需要安装 RouteDebugger 包(可通过 nuget 获得)以查看路由的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多