首页 > 解决方案 > 将 Google AMP 应用于 MVC Core 应用程序(替代 MVC Core 的显示模式)

问题描述

我有一个应用程序,它使用移动视图和桌面视图作为不同的 HTML 页面。现在我将其移至 ASP.NET Core。我正在尝试使用 ASP.NET Core MVC 创建一个 AMP 页面。

代码:

public class AmpViewLocationExpander : IViewLocationExpander {
    private const string ValueKey = "ampmode";
    public void PopulateValues(ViewLocationExpanderContext context) {
        // magic utility method that determines whether this is within an AMP context
        var isAmp = context.ActionContext.HttpContext.IsAmp();
        // persist the value on the context to allow the cache to consider this
        context.Values[ValueKey] = isAmp.ToString();
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
    IEnumerable<string> viewLocations) {
        // when in AMP mode
        if (context.Values.TryGetValue(ValueKey, out var isAmpValue) && isAmpValue == "True") {
            return ExpandAmpViewLocations(viewLocations);
        }
        // otherwise fall back to default locations
        return viewLocations;
    }

    private IEnumerable<string> ExpandAmpViewLocations(IEnumerable<string> viewLocations) {
        foreach (var location in viewLocations) {
            // yield the AMP version first
            yield return location.Replace("{0}", "{0}.amp");
            // then yield the normal version as a fallback
            yield return location;
        }
    }
}

我搜索了这个并在这个链接中实现了:Apply AMP using MVC Core,但它显示了这个错误:

“HttpContext”不包含“IsAmp”的定义,并且找不到接受“HttpContext”类型的第一个参数的可访问扩展方法“IsAmp”(您是否缺少 using 指令或程序集引用?)

标签: asp.net-coreasp.net-core-mvcamp-html

解决方案


推荐阅读