MVC4 Razor 自定义视图定位器 [英] MVC4 Razor Custom View Locator

查看:33
本文介绍了MVC4 Razor 自定义视图定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个旨在为两个域提供服务的 MVC4 应用程序.我们的大部分内容将跨域共享,但有时我们需要根据请求来自哪个站点呈现不同的标记(使用 Razor).

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

解析视图时,我想先检查域特定文件夹,然后是通用视图文件夹.

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"
        };

        ...
}

然后我需要覆盖 FindViewFindPartialView 方法,以便它仅在请求来自正确的域时才尝试查找定位视图:

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 Razor 自定义视图定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆