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

Azure Web App(Windows)中ASP.Net 8.0 WebAPI URL含+字符报错求助

问题描述
  • 运行环境:Windows 环境的 Azure Web App,部署 ASP.NET 8.0 WebAPI 应用
  • 正常请求:GET xxx/v1.0/sync/testtest 可正常返回结果
  • 异常请求:GET xxx/v1.0/sync/test+text 返回错误:你正在查找的资源已被移除、更名或暂时不可用。
  • 本地测试两个请求均正常,其他特殊字符(如%、"等)也可正常处理,应用及 WebApp 无特殊配置
解决建议

1. 调整 Azure Web App 请求筛选设置

Windows 环境的 Azure Web App 默认启用请求筛选模块,+ 字符在 URL 中常被解码为空格,部分安全规则会默认拦截这类路径。可通过两种方式修改:

  • 在 Web App 的 配置 > 应用程序设置 中,添加/修改 REQUEST_FILTERING_ALLOW_DOUBLE_ESCAPING 为 true
  • 在项目的 web.config 中添加配置,允许未转义字符:
    <system.webServer>
      <security>
        <requestFiltering allowDoubleEscaping="true" />
      </security>
    </system.webServer>
    

2. 配置 ASP.NET Core 宽松路径匹配

ASP.NET 8 默认路由规则对特殊字符限制较严,可在 Program.cs 中调整路由配置:

// 注册自定义路由约束
builder.Services.Configure<RouteOptions>(options =>
{
    options.ConstraintMap.Add("allowplus", typeof(AllowPlusConstraint));
});

// 应用路由时使用约束
app.MapControllers().WithOptions(options =>
{
    options.SuppressCheckForUnhandledSecurityMetadata = true;
});

自定义约束类(允许路径包含+):

public class AllowPlusConstraint : IRouteConstraint
{
    public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var value = values[routeKey]?.ToString();
        return value?.All(c => char.IsLetterOrDigit(c) || c == '+') ?? true;
    }
}

在接口路由中使用约束:

[HttpGet("/v1.0/sync/{data:allowplus}")]
public IActionResult Sync(string data)
{
    return Ok(data);
}

3. 处理 URL 编码逻辑

Azure 环境的 URL 解码逻辑可能与本地不同,可通过中间件手动处理路径中的+:

app.Use(async (context, next) =>
{
    if (context.Request.Path.HasValue)
    {
        var decodedPath = context.Request.Path.Value.Replace("+", "%2B");
        context.Request.Path = new PathString(Uri.UnescapeDataString(decodedPath));
    }
    await next();
});

也可要求客户端将+编码为%2B后再发送请求,服务器端会自动解码为+。

4. 排查安全扩展规则

若使用 Azure Front Door、Web Application Firewall(WAF)等安全扩展,可能会拦截带+的请求。可暂时禁用相关扩展测试,确认后在 WAF 规则中添加例外,允许 URL 路径包含+字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:22:45