在Visual Studio上运行网站项目在本地失败,出现http 404找不到页面错误

时间:2018-11-21 16:11:37

标签: asp.net-mvc visual-studio routing

我一直在从事一个项目,当我回到该项目并尝试使用Ctr + F5运行该项目时,我将其离开了大约一个星期,它重定向到未在route config中定义的URL。像这样的http://localhost:53771/Views/Home/Index.cshtml并遇到HTTP 404:找不到错误。虽然我的路由配置像这样,但如果我在r + F5前面输入CORRET URL MYSELF,它就可以正常工作,但它会重定向到路由配置中未定义的URL。像这样http://localhost:53771

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

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

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

我开始调试该项目,看来该项目从未出现在我的HomeController上。我只有一个名为Home的控制器,当我删除Home控制器的所有代码时,它的行为仍然相同。另一件事似乎是错误的,它甚至在使用http://localhost:53771/Views/Home/Index.cshtml函数之前就创建了URL RegisterRoutes。问题是局部的,如果需要,这是我的global.asax。感谢您的帮助

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace ML_Projectname
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            MvcHandler.DisableMvcResponseHeader = true;
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            MvcHandler.DisableMvcResponseHeader = true;


        }



        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Remove("X-Powered-By");
            HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
            HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
            HttpContext.Current.Response.Headers.Remove("Server");

        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您的路由或应用程序没有任何问题。 Visual Studio的默认启动操作(通过右键单击项目->选择属性->选择Web进行查看)是“当前页面”。如果您在Visual Studio中运行项目时正在查看剃刀视图(例如/Views/Home/Index.cshtml),Visual Studio将尝试直接导航到该资源。直接请求剃刀视图在MVC应用程序的上下文中无效,最终您会看到404错误。

为避免这种情况,您可以将起始URL设置为特定的URL(例如:http://localhost:53771),甚至更简单,在运行之前打开并查看其中一个服务器端文件(例如:HomeController.cs)。您的项目通过Visual Studio。

tldr版本:这是Visual Studio中设置的问题,而不是应用程序代码的问题