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

如何保持Uri中的路径不被编码?C# UriBuilder使用问题

解决UriBuilder创建Uri时路径中问号被编码的问题

你遇到的问题根源在于:把包含查询参数的完整字符串传给了UriBuilder的Path属性——UriBuilder会自动编码路径中的特殊字符(比如?),导致生成的URL里?变成了%3F,浏览器无法正常识别查询参数。

正确的做法是将路径和查询参数分开设置:

  • Path属性仅填写纯路径部分
  • 查询参数单独放到Query属性中(无需添加开头的?,UriBuilder会自动补全)

修改后的代码示例:

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var newLocation = new UriBuilder()
        {
            Scheme = Uri.UriSchemeHttps,
            Host = "localhost",
            Path = "/WebResource.axd",
            Query = "d=0"
        }.Uri;
        
        Console.WriteLine($"Hello World {newLocation}");
    }
}

运行输出:

Hello World
Hello World https://localhost/WebResource.axd?d=0

内容的提问来源于stack exchange,提问作者I am not Fat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:55:16