简体   繁体   English

ASP.NET MVC路由:尽管默认情况下已声明索引(使用区域),但仍需要在URL中使用索引

[英]ASP.NET MVC Routing: Need to use Index in URL despite it being declared in defaults (using Areas)

I have searched but no solutions seem to work for me. 我已经搜索过,但似乎没有解决方案适合我。 I have a web forms VS2013 solution and I've been adding MVC to this using an Area. 我有一个Web表单VS2013解决方案,并且我一直在使用Area将MVC添加到其中。 I have got everything working when I specify eg: http://localhost:51961/MVC/contractfiles/index/ 当我指定时,我一切正常,例如: http://localhost:51961/MVC/contractfiles/index/

This works fine, but I need it to go to the same page when i use: 这工作正常,但是当我使用时,我需要它转到同一页面:

http://localhost:51961/MVC/contractfiles/

instead I get HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory. 相反,我收到HTTP错误403.14-禁止-Web服务器配置为不列出此目录的内容。

My Area registration is: 我的区域注册是:

    namespace PublicHealthCMS_L3.Areas.MVC
    {
        public class MVCAreaRegistration : AreaRegistration 
        {
            public override string AreaName 
            {
                get 
                {
                    return "MVC";
                }
            }

            public override void RegisterArea(AreaRegistrationContext context) 
            {
                context.MapRoute(
                    "MVC_default",
                    "MVC/{controller}/{action}/{id}",
                    new { action = "Index", id = UrlParameter.Optional },
                    namespaces: new[] {"PublicHealthCMS_L3.Areas.MVC.Controllers" }
                );
            }
        }
    }

And my contractfiles controller: 和我的contractfiles控制器:

namespace PublicHealthCMS_L3.Areas.MVC.Controllers
{
    public class ContractFilesController : Controller
    {
        private PublicHealthCMSEntitiesMVC db = new PublicHealthCMSEntitiesMVC();

        // GET: MVC/ContractFiles
        public ActionResult Index()
        {
            int ContractID = MySession.Current.ContractID;
            return View(db.pr_File_Select(242).ToList());
        }

Thanks for any help 谢谢你的帮助

Main route: 主要路线:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "contractfiles", action = "Index", id = UrlParameter.Optional },
                namespaces: new string[] { "PublicHealthCMS_L3.Controllers" }
            );

            //.DataTokens = new RouteValueDictionary(new { area = "MVC" } );

        }
    }
}

Global.asax Application_Start Global.asax Application_Start

void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup     
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);            


            //RegisterRoutes(RouteTable.Routes);

        }

I also have some webapi routes, WebApiConfig.cs: 我也有一些webapi路由WebApiConfig.cs:

namespace PublicHealthCMS_L3
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

web.config: web.config中:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="PublicHealthCMS_L3.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" /></configSections>
  <appSettings>
    <add key="RouteDebugger:Enabled" value="false"/>
    <add key="MessageNoContractSelected" value="No contract is selected, please click Search and select a contract" />
    <add key="MessageDeleteRecordFilesExist" value="This record has associated files, please expand the record and remove the files first before the record can be deleted" />
    <add key="Version" value="1.02" />
  <add key="RouteDebugger:Enabled" value="true" /></appSettings>
  <connectionStrings>   
    <add name="PublicHealthCMSConnectionString" connectionString="Data Source=bcvPHDEVSQL;User Id=PublicHealth_User; Password=;Initial Catalog=PublicHealthCMS;" providerName="System.Data.SqlClient" />
    <add name="PublicHealthCMSEntities" connectionString="metadata=res://*/CRMModel.csdl|res://*/CRMModel.ssdl|res://*/CRMModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=BCVPHDEVSQL;initial catalog=PublicHealthCMS;User Id=PublicHealth_User; Password=;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="PublicHealthCMSEntitiesMVC" connectionString="metadata=res://*/Areas.MVC.Models.CMSModel.csdl|res://*/Areas.MVC.Models.CMSModel.ssdl|res://*/Areas.MVC.Models.CMSModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=bcvPHDEVSQL;initial catalog=PublicHealthCMS;user id=PublicHealth_User;password=;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

  <system.web>
    <httpRuntime maxRequestLength="20480" />
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false" />
    <add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" /></httpHandlers>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <!--<add assembly="System.Data.Entity, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />-->
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
      </assemblies>
      <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </buildProviders>
    </compilation>
    <authentication mode="Windows">
    </authentication>
    <authorization>
      <deny users="?" />
      <!-- This denies access to the Anonymous/unregistered user -->
      <allow users="*" />
      <!-- This allows access to all registered users -->
    </authorization>
    <identity impersonate="false" />

    <pages controlRenderingCompatibilityVersion="4.0"></pages>
  <!-- Glimpse: This can be commented in to add additional data to the Trace tab when using WebForms
        <trace writeToDiagnosticsTrace="true" enabled="true" pageOutput="false"/> --><httpModules>
            <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" />
        </httpModules></system.web>
  <system.webServer>

    <!--<directoryBrowse enabled="true" />-->
    <modules runAllManagedModulesForAllRequests="true"><add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" /></modules>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />



      <!-- Your other remove tags-->
      <!--
      <remove name="UrlRoutingModule-4.0" />
       -->
      <!--Your other add tags-->
      <!--
      <add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition="" />-->
    <add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" /></handlers>
    <defaultDocument>
      <files>
        <!--<add value="Search.aspx" />-->
        <add value="Index.cshtml" />
      </files>
    </defaultDocument>
  </system.webServer>
  <system.serviceModel>
    <bindings />
    <client />
  </system.serviceModel>
  <applicationSettings>
    <PublicHealthCMS_L3.Properties.Settings>
      <setting name="PublicHealthCMS_L3_ActiveDirectory_ActiveDirectory" serializeAs="String">
        <value>http://bcvmbiis02/tools/ActiveDirectory.asmx</value>
      </setting>
    </PublicHealthCMS_L3.Properties.Settings>
  </applicationSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
      <!-- 
          For more information on how to configure Glimpse, please visit http://getglimpse.com/Help/Configuration
          or access {your site}/Glimpse.axd for even more details and a Configuration Tool to support you. 
      -->
    </glimpse></configuration>

Also, the web.config within the MVC area: 此外,MVC区域内的web.config:

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="PublicHealthCMS_L3" />

      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <!--<add key="webpages:Enabled" value="false" />-->
  </appSettings>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

Replace this 取代这个

new { action = "Index", id = UrlParameter.Optional }

with this: 有了这个:

new { controller="ContractFiles", action = "Index", id = UrlParameter.Optional }

And try to rebuild the project. 并尝试重建项目。 I just verified - and it works 我刚刚验证了-并且有效

Try to add it in WebConfig file: 尝试将其添加到WebConfig文件中:

 <system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/> 
 </system.webServer>

and

    <system.webServer>
      <defaultDocument>
       <files>
      <add value="index.cshtml" />
      </files>
     </defaultDocument>
    <directoryBrowse enabled="true" />
    </system.webServer>

Please see the answer from " IIS not running ASP.NET MVC application " 请从“ IIS未运行ASP.NET MVC应用程序 ”中查看答案

This was a strange error and I've 'resolved' it by adding a new controller and copying and pasting everything from the existing controller into this new one. 这是一个奇怪的错误,我通过添加新控制器并将所有内容从现有控制器复制并粘贴到此新控制器中来“解决”。 The new one works fine. 新的工作正常。 Very irritating that I've spent 3-4 days trying to solve a problem that is obviously some sort of bug as the new controller is exactly the same as the existing one but works fine. 我花了3-4天的时间来解决一个很明显是某种bug的问题,这很令人恼火,因为新控制器与现有控制器完全相同,但效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM