asp.net - mvc3中如何实现URL重写?

标签 asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我在 MVC3 中的目录结构如下。

enter image description here

我安装了 URL 重写 2.0。我添加了 URL 重写。

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=152368
  -->
<configuration>
  <configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>

    <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
    <section name="combres" type="Combres.ConfigSectionSetting, Combres, Version=2.2, Culture=neutral, PublicKeyToken=1ca6b37997dd7536" />
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
      <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
      <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
      <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
      <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
    </sectionGroup>
    <section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
  </configSections>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="elmah.mvc.disableHandler" value="false" />
    <add key="elmah.mvc.disableHandleErrorFilter" value="false" />
    <add key="elmah.mvc.requiresAuthentication" value="false" />
    <add key="elmah.mvc.IgnoreDefaultRoute" value="false" />
    <add key="elmah.mvc.allowedRoles" value="*" />
    <add key="elmah.mvc.allowedUsers" value="*" />
    <add key="elmah.mvc.route" value="elmah" />
    <add key="CombresSectionName" value="combres" />
  </appSettings>
  <system.web>
    <customErrors mode="RemoteOnly"></customErrors>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="Combres" />
        <add namespace="Combres.Mvc" />
      </namespaces>
    </pages>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      <add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
      <add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" />
    </httpHandlers>
    <!-- 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="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" />
    </httpModules>
  </system.web>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="WebFormToMyPage" stopProcessing="true">
          <match url="^WEBFORM1.aspx" />
          <action type="Redirect" url="MyDirectory/MyPage" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
      <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" />
    </modules>
    <handlers>
      <add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
      <add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
    </handlers>

  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="AjaxMin" publicKeyToken="21ef50ce11b5d80f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.84.4790.14405" newVersion="4.84.4790.14405" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.2.13.0" newVersion="2.2.13.0" />
      </dependentAssembly>
    </assemblyBinding>
    <!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). -->
    <legacyHMACWarning enabled="0" />
    <!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
             to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it.
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
         -->
  </runtime>
  <elmah></elmah>
  <dotless minifyCss="false" cache="true" web="false" />
  <combres definitionUrl="~/App_Data/combres.xml" />
  <system.net>
    <defaultProxy enabled="true" />
    <settings>
      <!-- This setting causes .NET to check certificate revocation lists (CRL) 
                 before trusting HTTPS certificates.  But this setting tends to not 
                 be allowed in shared hosting environments. -->
      <!--<servicePointManager checkCertificateRevocationList="true"/>-->
    </settings>
  </system.net>
  <dotNetOpenAuth>
    <messaging>
      <untrustedWebRequest>
        <whitelistHosts>
          <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
          <!--<add name="localhost" />-->
        </whitelistHosts>
      </untrustedWebRequest>
    </messaging>
    <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
    <reporting enabled="true" />
    <!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
    <!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
    <openid>
      <relyingParty>
        <security requireSsl="false">
          <!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. -->
          <!--<trustedProviders rejectAssertionsFromUntrustedProviders="true">
                        <add endpoint="https://www.google.com/accounts/o8/ud" />
                    </trustedProviders>-->
        </security>
        <behaviors>
          <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                         with OPs that use Attribute Exchange (in various formats). -->
          <add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
        </behaviors>
      </relyingParty>
      <provider></provider>
    </openid>
  </dotNetOpenAuth>
  <uri>
    <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
             which is necessary for OpenID urls with unicode characters in the domain/host name.
             It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
    <idn enabled="All" />
    <iriParsing enabled="true" />
  </uri>
  <glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
    <!-- If you are having issues with Glimpse, please include this. It will help us figure out whats going on. 
      <logging level="Trace" />-->
    <!-- Want to use Glimpse on a remote server? Ignore the LocalPolicy by removing this comment.-->
      <runtimePolicies>
        <ignoredTypes>
          <add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet"/>
        </ignoredTypes>
      </runtimePolicies>
  </glimpse>
</configuration>

当有人尝试输入以下网址时

http://localhost/webform1.aspx

它应该变成如下所示...

http://localhost/MyDirectory/MyPage

我怎样才能实现这一目标?

最佳答案

据我所知,您实际上想要两件事:

  1. 当用户导航到 /MyDirectory/MyPage 时,您希望返回 WebForm1.aspx 呈现的任何内容。
  2. 当用户导航到 /WebForm1.aspx 时,您希望将他重定向到 /MyDirectory/MyPage 以便地址栏中的 URL 发生变化。

对于第一个,请在默认路由之前添加此路由:

routes.MapPageRoute("MyPage", "MyDirectory/MyPage", "~/WebForm1.aspx");

这将使 /MyDirectory/MyPage 成为 /WebForm1.aspx 的别名。

对于第二个,将以下重写规则添加到 web.config 文件的 system.webServer 部分:

<rewrite>
    <rules>
            <rule name="WebFormToMyPage" stopProcessing="true">
                <match url="^WebForm1.aspx" />
                <action type="Redirect" url="MyDirectory/MyPage" />
            </rule>
    </rules>
</rewrite>

关于asp.net - mvc3中如何实现URL重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597529/

相关文章:

c# - 在没有 OuterXML 的情况下验证(和查询)XmlElement 内容?

asp.net - 在 ASP.Net Core Identity 中获取当前主体作为我的自定义应用程序用户

asp.net - 获取 OleDbDataReader ASP.NET (VB) 返回的行数

c# - 如何在 Identity 2 中将 Id 属性从字符串转换为 int

c# - ConnectionStrings 或 AppSettings 的存储库

asp.net-mvc - 在 Asp.Net MVC View 中,不呈现 Controller 对模型所做的更改

javascript - JQuery 设置后找不到 .NET 隐藏字段值

c# - 不会调用 HttpPost

.net - 将@section 放入@if .net mvc 3

javascript - MVC 3 ValidationMessageFor() 没有出现