使用多个Web应用程序共享控制器和视图

blu*_*blu 20 razor asp.net-mvc-3

我想将控制器和视图分解为单独的类库,以便可以在多个ASP.NET MVC 3应用程序中重用它们.使用单独的程序集时控制器部分不是问题,但是让视图引擎定位视图是.

我最终使用将你的asp.net mvc Razor视图编译成一个单独的dll.

我错过了一种更简单的方法吗?

Car*_*ick 18

我修改了这里发布的想法,与MVC3合作.它非常快速和简单.唯一的小缺点是共享视图需要嵌入资源,因此需要编译.

  • 将您的共享视图(.cshtml,.vbhtml文件)放入库项目中.(我在这个项目中也有一些共享控制器.)如果你想使用应用程序中的_Layout.cshtml,请确保在共享视图中包含指向它的_ViewStart.cshtml.

  • 在库项目中,将所有视图的"构建操作"属性设置为"嵌入式资源".

  • 在库项目中添加以下代码,该代码将视图的内容写入tmp/Views目录.

.

public class EmbeddedResourceViewEngine : RazorViewEngine
{
    public EmbeddedResourceViewEngine()
    {
        ViewLocationFormats = new[] {
        "~/Views/{1}/{0}.aspx",
        "~/Views/{1}/{0}.ascx",
        "~/Views/Shared/{0}.aspx",
        "~/Views/Shared/{0}.ascx",
        "~/Views/{1}/{0}.cshtml",
        "~/Views/{1}/{0}.vbhtml",
        "~/Views/Shared/{0}.cshtml",
        "~/Views/Shared/{0}.vbhtml",
        "~/tmp/Views/{0}.cshtml",
        "~/tmp/Views/{0}.vbhtml"
    };
        PartialViewLocationFormats = ViewLocationFormats;

        DumpOutViews();
    }

    private static void DumpOutViews()
    {
        IEnumerable<string> resources = typeof(EmbeddedResourceViewEngine).Assembly.GetManifestResourceNames().Where(name => name.EndsWith(".cshtml"));
        foreach (string res in resources) { DumpOutView(res); }
    }

    private static void DumpOutView(string res)
    {
        string rootPath = HttpContext.Current.Server.MapPath("~/tmp/Views/");
        if (!Directory.Exists(rootPath))
        {
            Directory.CreateDirectory(rootPath);
        }

        Stream resStream = typeof(EmbeddedResourceViewEngine).Assembly.GetManifestResourceStream(res);
        int lastSeparatorIdx = res.LastIndexOf('.');
        string extension = res.Substring(lastSeparatorIdx + 1);
        res = res.Substring(0, lastSeparatorIdx);
        lastSeparatorIdx = res.LastIndexOf('.');
        string fileName = res.Substring(lastSeparatorIdx + 1);

        Util.SaveStreamToFile(rootPath + fileName + "." + extension, resStream);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Adrian的StreamToFile编写器,在这里找到.

  • 在应用程序的Global.asax.cs中添加:

.

public static void RegisterCustomViewEngines(ViewEngineCollection viewEngines)
{
   //viewEngines.Clear(); //This seemed like a bad idea to me.
   viewEngines.Add(new EmbeddedResourceViewEngine());
}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    RegisterCustomViewEngines(ViewEngines.Engines);
}
Run Code Online (Sandbox Code Playgroud)


san*_*oIT 3

看看mvc contrib的可移植区域: http://www.lostechies.com/blogs/hex/archive/2009/11/01/asp-net-mvc-portable-areas-via-mvccontrib.aspx 它们是专门制作的以此目的。如果你走那条路,你需要维护的代码就会更少;-)