当前,我们正在构建一个Web应用程序,首先是台式机,需要针对特定页面的设备特定的Razor页面。这些页面与桌面版本确实不同,因此在此处使用响应能力是没有意义的。
我们尝试实现自己的IViewLocationExpander,还尝试使用MvcDeviceDetector库(基本上是在做同样的事情)。设备类型的检测没有问题,但是由于某种原因,设备特定页面没有被拾取,并且它不断地退回到默认的Index.cshtml。 ( edit:我们正在考虑基于IPageConvention,IPageApplicationModelProvider或某些东西实现...;-))
Index.mobile.cshtml Index.cshtml
我们使用MvcDeviceDetector的示例添加了以下代码:
public static IMvcBuilder AddDeviceDetection(this IMvcBuilder builder)
{
builder.Services.AddDeviceSwitcher<UrlSwitcher>(
o => { },
d => {
d.Format = DeviceLocationExpanderFormat.Suffix;
d.MobileCode = "mobile";
d.TabletCode = "tablet";
}
);
return builder;
}
并添加一些路由映射
routes.MapDeviceSwitcher();
我们希望在Chrome中选择电话仿真时会看到Index.mobile.cshtml,但这没有发生。
编辑注意:
修改2 我认为解决方案将与您实现特定于文化的Razor Pages的方式相同(这对我们来说也是未知的;-)。基本MVC支持Index.en-US.cshtml
答案 0 :(得分:1)
如果这是Razor Pages应用程序(与MVC应用程序相对),那么我认为IViewLocationExpander
接口对您来说并没有太大用处。据我所知,它仅适用于部分页面,而不适用于可路由页面(即具有@page
指令的页面)。
您可以做的是使用中间件确定请求是否来自移动设备,然后将要执行的文件更改为以.mobile
结尾的文件。这是一个非常粗糙且易于实现的实现:
public class MobileDetectionMiddleware
{
private readonly RequestDelegate _next;
public async Task Invoke(HttpContext context)
{
if(context.Request.IsFromAMobileDevice())
{
context.Request.Path = $"{context.Request.Path}.mobile";
}
await _next.Invoke(context);
}
}
由您决定如何实现IsFromAMobileDevice
方法来确定用户代理的性质。没有什么可以阻止您使用可以为您可靠地执行检查的第三方库。另外,您可能只想在某些情况下(例如,在所请求页面的设备特定版本中)更改路径。
尽早在您的Configure
方法中注册它:
app.UseMiddleware<MobileDetectionMiddleware>();
答案 1 :(得分:0)
我终于找到了基于约定的方法。我已经实现了IViewLocationExpander以便处理基本Razor视图(包括布局)的设备处理,并且已经实现了IPageRouteModelConvention + IActionConstraint来处理Razor页面的设备。
注意: 该解决方案似乎仅在ASP.NET Core 2.2及更高版本上有效。出于某种原因,2.1.x及以下版本将在添加约束(可能已修复)后清除约束(在析构函数中使用断点进行测试)。
现在我可以在MVC和Razor页面中都拥有/Index.mobile.cshtml /Index.desktop.cshtml等。
注意:此解决方案还可用于实现特定于语言/区域性的Razor页面(例如/Index.en-US.cshtml /Index.nl-NL.cshtml)
public class PageDeviceConvention : IPageRouteModelConvention
{
private readonly IDeviceResolver _deviceResolver;
public PageDeviceConvention(IDeviceResolver deviceResolver)
{
_deviceResolver = deviceResolver;
}
public void Apply(PageRouteModel model)
{
var path = model.ViewEnginePath; // contains /Index.mobile
var lastSeparator = path.LastIndexOf('/');
var lastDot = path.LastIndexOf('.', path.Length - 1, path.Length - lastSeparator);
if (lastDot != -1)
{
var name = path.Substring(lastDot + 1);
if (Enum.TryParse<DeviceType>(name, true, out var deviceType))
{
var constraint = new DeviceConstraint(deviceType, _deviceResolver);
for (var i = model.Selectors.Count - 1; i >= 0; --i)
{
var selector = model.Selectors[i];
selector.ActionConstraints.Add(constraint);
var template = selector.AttributeRouteModel.Template;
var tplLastSeparator = template.LastIndexOf('/');
var tplLastDot = template.LastIndexOf('.', template.Length - 1, template.Length - Math.Max(tplLastSeparator, 0));
template = template.Substring(0, tplLastDot); // eg Index.mobile -> Index
selector.AttributeRouteModel.Template = template;
var fileName = template.Substring(tplLastSeparator + 1);
if ("Index".Equals(fileName, StringComparison.OrdinalIgnoreCase))
{
selector.AttributeRouteModel.SuppressLinkGeneration = true;
template = selector.AttributeRouteModel.Template.Substring(0, Math.Max(tplLastSeparator, 0));
model.Selectors.Add(new SelectorModel(selector) { AttributeRouteModel = { Template = template } });
}
}
}
}
}
protected class DeviceConstraint : IActionConstraint
{
private readonly DeviceType _deviceType;
private readonly IDeviceResolver _deviceResolver;
public DeviceConstraint(DeviceType deviceType, IDeviceResolver deviceResolver)
{
_deviceType = deviceType;
_deviceResolver = deviceResolver;
}
public int Order => 0;
public bool Accept(ActionConstraintContext context)
{
return _deviceResolver.GetDeviceType() == _deviceType;
}
}
}
public class DeviceViewLocationExpander : IViewLocationExpander
{
private readonly IDeviceResolver _deviceResolver;
private const string ValueKey = "DeviceType";
public DeviceViewLocationExpander(IDeviceResolver deviceResolver)
{
_deviceResolver = deviceResolver;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
var deviceType = _deviceResolver.GetDeviceType();
if (deviceType != DeviceType.Other)
context.Values[ValueKey] = deviceType.ToString();
}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var deviceType = context.Values[ValueKey];
if (!string.IsNullOrEmpty(deviceType))
{
return ExpandHierarchy();
}
return viewLocations;
IEnumerable<string> ExpandHierarchy()
{
var replacement = $"{{0}}.{deviceType}";
foreach (var location in viewLocations)
{
if (location.Contains("{0}"))
yield return location.Replace("{0}", replacement);
yield return location;
}
}
}
}
public interface IDeviceResolver
{
DeviceType GetDeviceType();
}
public class DefaultDeviceResolver : IDeviceResolver
{
public DeviceType GetDeviceType() => DeviceType.Mobile;
}
public enum DeviceType
{
Other,
Mobile,
Tablet,
Normal
}
启动
services.AddMvc(o => { })
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorOptions(o =>
{
o.ViewLocationExpanders.Add(new DeviceViewLocationExpander(new DefaultDeviceResolver()));
})
.AddRazorPagesOptions(o =>
{
o.Conventions.Add(new PageDeviceConvention(new DefaultDeviceResolver()));
});