MVC4剃刀自定义视图定位器 [英] MVC4 Razor Custom View Locator
问题描述
我的工作,旨在服务两个领域的应用MVC4。我们的大部分内容将在整个域共享,但有时我们需要处理不同的标记(用剃刀),这取决于网站的要求是从哪里来的。
I'm working on an MVC4 application that is designed to service two domains. Most of our content will be shared across the domains, but sometimes we will need to render different markup (using Razor) depending on which site the request came from.
在理想情况下,我想一个基于约定的方法,让我有一个文件夹结构是这样的:
Ideally, I want a convention-based approach that allows me to have a folder structure like this:
Views
+ Domain1
+ ControllerName
View1
View2
+ Domain2
+ ControllerName
View1
+ ControllerName
View1
View2
在解决一个看法,我想首先检查特定于域的文件夹,然后一般views文件夹。
When resolving a view, I would like to check the domain-specific folder first, then the general views folder.
我的第一个想法是,以实现继承RazorViewEngine将互换根据请求域ViewLocationFormats串自定义视图引擎。不幸的是所有这些东西埋在VirtualPathProviderEngine,不能被重写。
My first thoughts were to implement a custom view engine that inherits RazorViewEngine that would swap the ViewLocationFormats strings depending on the request domain. Unfortunately all this stuff is buried in the VirtualPathProviderEngine and can't be overridden.
推荐答案
事实证明,答案是创造知道该领域特定文件夹的每个域自定义视图引擎(从RazorViewEngine继承):
It turns out that the answer was to create a custom view engine (inherited from RazorViewEngine) for each domain that knows about the domain-specific folders:
public class Domain1ViewEngine() : RazorViewEngine
{
...
ViewLocationFormats = new[]
{
"~/Views/Domain1/{1}/{0}.cshtml",
"~/Views/Domain1/Shared/{0}.cshtml"
};
...
}
然后我需要重写 FindView
和 FindPartialView
方法,所以它只能试图找到,如果找到意见请求是来自权域:
I then needed to override the FindView
and FindPartialView
methods so that it only attempted to find locate views if the request had come from the right domain:
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if ([THIS IS NOT THE RIGHT DOMAIN])
{
return new ViewEngineResult(new string[] { });
}
return base.FindView(controllerContext, viewName, masterName, useCache);
}
要完成我注册的Global.asax.cs
视图引擎以通常的方式的过程:
To complete the process I registered the view engine in Global.asax.cs
in the usual way:
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new Domain1ViewEngine());
ViewEngines.Engines.Add(new RazorViewEngine());
}
这篇关于MVC4剃刀自定义视图定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!