在ASP.NET Web Forms应用程序中将ASP.NET MVC文件托管在子文件夹中的最佳方法是什么?

3
我有一个ASP.NET 4.0 Web Forms应用程序,并需要在同一个Web中托管一个ASP.NET MVC应用程序(即在同一个IIS进程内 - 相同的会话、模块等)。
只要两个应用程序的文件夹/文件位于根文件夹中,这很容易实现。
如何干净地允许MVC文件全部包含在子文件夹中?
我有一个视图引擎,可以添加子文件夹的位置格式。这使得所有控制器/视图工作正常,但我需要一个好的解决方案来处理内容文件。目前,我必须小心确保MVC应用程序中的所有路径都指向MVC子文件夹的名称,例如:
Url.Content("~/mvc/Content/Site.css")

有哪些稳定的选项可以实现这一点? 我不希望任何请求进出Web Forms受到影响。这个逻辑应该只操纵MVC引擎内可以解析的URL(或操作除Web Forms引擎单独可以解决的URL之外的所有URL)。 编辑:客户要求两个站点共享相同的IIS会话,因此暂时无法使用单独的应用程序。目前不想在IIS进程之间共享会话。

你能在IIS站点内创建子应用程序吗?(IIS站点>添加应用程序) - jorgebg
@jorgebg,这是客户的要求,两个站点共享相同的IIS会话,因此单独的应用程序会使其更难以实现/可靠地维护。 - Joseph Gabriel
@heiserman:您可以将MVC项目集成到WebForms项目中http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx 我在一些项目中也在做同样的事情,效果很好,因为您可以重用一些资源(CSS、图像)。 - Eduardo Molteni
@heiserman:我将所有与MVC相关的东西都放在“视图”文件夹下。每个视图都有自己的文件夹和相关的控制器。显然,控制器使用不同的命名空间。模型和图片是共享的。非常好用。 - Eduardo Molteni
我有一个视图引擎,可以为子文件夹添加位置格式。你怎么做到的?这对我很有帮助。 - SwissCoder
显示剩余3条评论
2个回答

3

我会创建一组URL助手扩展,以帮助我考虑这些因素。

扩展类

namespace Core.Extensions{
   public static class UrlHelperExtensions
   {
      public static string Image(this UrlHelper helper, string fileName)
      {
        return helper.Content("~/mvc/Content/Images/" + fileName);
      }

      public static string Stylesheet(this UrlHelper helper, string fileName)
      {
        return helper.Content("~/mvc/Content/Css/" + fileName);
      }

      public static string Script(this UrlHelper helper, string fileName)
      {
        return helper.Content("~/mvc/Content/Scripts/" + fileName);
      }
   }
}

Web.Config

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.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="Core.Extensions" />  <-- Add your extension namespace here
      </namespaces>
    </pages>
  </system.web.webPages.razor>

在视图中的使用

<link href="@Url.Stylesheet("site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Script("jquery-1.7.1.min.js")" type="text/javascript"></script>
<img src="@Url.Image("MyImageName.jpg")" />

<!--CSS in a sub directory from your root that you specified in your Extension class -->
<link href="@Url.Stylesheet("SomeDirectory/otherCss.css")" rel="stylesheet" type="text/css"/>

1
一个可行的解决方案是为MVC应用程序创建一个子域,例如mvc.mydomain.com。它提供了一个清晰的应用程序分离,易于集成,并且不需要额外的域名。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接