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

如何在ASP.NET MVC(Umbraco)应用中避免缺失User-Agent时的NullReferenceException

解决无User-Agent请求导致的NullReferenceException问题

问题原因分析

你的错误出在FileMappingModule.MapContent.Is_spider()方法中:TryBooking请求未携带User-Agent头,代码直接访问该请求头时触发了空引用异常。另外,你尝试的ActionFilterAttribute无效,是因为这个模块的Context_BeginRequest事件在ASP.NET请求管道的BeginRequest阶段执行,这个时机远早于ActionFilter的执行阶段,过滤器根本没机会在模块运行前处理请求头。

可行解决方案

1. 预填充默认User-Agent(推荐,无需修改模块代码)

在Global.asax的Application_BeginRequest方法中提前为无User-Agent的请求设置默认值。注意不能直接修改Request.Headers(只读集合),需要操作ServerVariables:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var request = HttpContext.Current.Request;
    if (string.IsNullOrEmpty(request.ServerVariables["HTTP_USER_AGENT"]))
    {
        // 设置一个合理的默认UA,比如模拟TryBooking的请求标识
        request.ServerVariables.Set("HTTP_USER_AGENT", "TryBooking/1.0");
    }
}

这样Is_spider()方法读取User-Agent时就不会拿到null,避免空引用。

2. 修改爬虫检查方法的空值处理逻辑

找到FileMappingModule.MapContent.Is_spider()的源码,添加空值判断:

private bool Is_spider()
{
    // 先判断UA是否为空,为空则直接返回false(不判定为爬虫)
    string userAgent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]?.ToLower() ?? string.Empty;
    if (string.IsNullOrEmpty(userAgent))
        return false;
    
    // 保留原有的爬虫关键词检查逻辑
    return userAgent.Contains("bot") || userAgent.Contains("spider") || userAgent.Contains("crawler");
}

修改后即使没有User-Agent,也不会触发空引用,同时默认不将该请求判定为爬虫。

3. 直接禁用爬虫检查模块

如果你的业务不需要这个爬虫检查功能,可以在Web.config中移除该模块的注册:

<system.webServer>
  <modules>
    <!-- 注释或删除FileMappingModule的注册项 -->
    <!-- <add name="FileMappingModule" type="你的命名空间.FileMappingModule, 程序集名称" /> -->
  </modules>
</system.webServer>

如果模块是通过代码动态注册的,可在Global.asax中取消其BeginRequest事件的绑定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:52:44