在ASP.NET MVC中自动切换AMP的视图 [英] Automatically switching views for AMP in ASP.NET MVC
问题描述
我想使用.NET Core 2.0在ASP.NET MVC中创建我的网站的AMP版本.以前,我过去曾在.Net框架上对DisplayModeProvider
实例进行过一些工作,但这在.NET Core中似乎不是一个选择.
I want to create and AMP version of my website in ASP.NET MVC using .NET Core 2.0. Previously I had done some work with DisplayModeProvider
instances in tha past on .Net framework, but that does not seem to be an option in .NET Core.
我想做的是,当我的URL从/amp
开始时,将视图名称更改为index.amp.cshtml
而不是index.cshtml
.在.NET Core中实现此目标的最佳方法是什么?
What I want to be able to do is alter the view names to be index.amp.cshtml
rather than index.cshtml
when my URL starts iwth /amp
. What's the best way to achieve this in .NET Core?
推荐答案
您可以使用IViewLocationExpander
执行类似的操作.碰巧的是,几天前我正在玩这个游戏,所以我要准备一些代码示例.如果您创建这样的内容:
You can do something like this using IViewLocationExpander
. As it happens, I was playing with this a few days ago so I have some code samples to hand. If you create something like this:
public class AmpViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
var contains = context.ActionContext.HttpContext.Request.Query.ContainsKey("amp");
context.Values.Add("AmpKey", contains.ToString());
var containsStem = context.ActionContext.HttpContext.Request.Path.StartsWithSegments("/amp");
context.Values.Add("AmpStem", containsStem.ToString());
}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
if (!(context.ActionContext.ActionDescriptor is ControllerActionDescriptor descriptor)) { return viewLocations; }
if (context.ActionContext.HttpContext.Request.Query.ContainsKey("amp")
|| context.ActionContext.HttpContext.Request.Path.StartsWithSegments("/amp")
)
{
return viewLocations.Select(x => x.Replace("{0}", "{0}.amp"));
}
return viewLocations;
}
}
iViewLocationExpander
可以在Microsoft.AspNetCore.Mvc.Razor
然后在Startup.cs
中的Configure Services
方法中,添加以下内容:
Then in your Configure Services
method in Startup.cs
, add the following:
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new AmpViewLocationExtender());
});
此操作将在URL以/amp
开头或查询字符串键为amp
的任何时候更新在.cshtml
之前插入.amp
的每个请求的视图位置.如果您的AMP视图不存在,它可能会爆炸一些,我尚未对其进行全面测试,但这应该可以帮助您入门.
What this will do is update the view locations per request to insert .amp
before .cshtml
any time the URL either starts with /amp
or there is a query string key of amp
. If your AMP views don't exist, it might blow-up a little, I've not fully tested it, but it should get you started.
这篇关于在ASP.NET MVC中自动切换AMP的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!