You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Umbraco 12本地实例检测浏览器/用户代理报错:Request不存在

Umbraco 12 设备检测编译错误解决方案

问题根源

Umbraco 12 基于 ASP.NET Core 构建,彻底抛弃了传统 ASP.NET 的 System.Web 栈,原来视图中直接使用的 Request 对象不再属于默认上下文,且 Request.Browser.IsMobileDevice 这类旧版 API 也已被移除。

解决步骤

1. 注入 HttpContext 访问器

在你的视图顶部添加注入语句,获取当前请求上下文:

@inject IHttpContextAccessor HttpContextAccessor

2. 替换设备检测逻辑

将原来的检测代码替换为基于 User-Agent 解析的逻辑(ASP.NET Core 不再提供内置的 Browser 检测):

@{
    var httpContext = HttpContextAccessor.HttpContext;
    bool isMobile = false;
    
    if (httpContext != null)
    {
        var userAgent = httpContext.Request.Headers["User-Agent"].ToString().ToLower();
        // 匹配移动设备,同时排除平板/iPad
        isMobile = userAgent.Contains("mobile") 
                   && !userAgent.Contains("ipad") 
                   && !userAgent.Contains("tablet");
    }
}

@if(isMobile)
{
    // 这里写你的移动端专属代码
}

3. 确认服务注册(可选)

如果你的项目中未自动注册 IHttpContextAccessor,在 Program.cs 中添加以下代码:

builder.Services.AddHttpContextAccessor();

进阶方案(可选)

如果需要更精准的设备检测(比如区分不同品牌设备、识别新型平板),可以使用第三方库(如 DeviceDetector.NET):

  1. 安装包:
dotnet add package DeviceDetectorNET
  1. 在视图中使用:
@using DeviceDetectorNET;

@{
    var httpContext = HttpContextAccessor.HttpContext;
    bool isMobile = false;
    
    if (httpContext != null)
    {
        var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
        var detector = new DeviceDetector(userAgent);
        detector.Parse();
        
        isMobile = detector.IsMobile() && !detector.IsTablet();
    }
}

内容的提问来源于stack exchange,提问作者Jamaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:01:23