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

在C#中为现有URL添加新查询字符串并重定向

C#实现URL添加查询参数并重定向

方法一:ASP.NET Web Forms环境

使用UriBuilder和HttpUtility.ParseQueryString安全处理URL与查询参数,避免手动拼接引发的编码问题:

using System;
using System.Web;

public void RedirectWithAddedParams()
{
    // 原URL
    string originalUrl = "http://localhost/somesite/index.php?Filename=somefile.txt&Filepath=E:\\myfolder";
    
    // 解析原URL
    UriBuilder uriBuilder = new UriBuilder(originalUrl);
    
    // 获取可修改的查询字符串集合
    var queryParams = HttpUtility.ParseQueryString(uriBuilder.Query);
    
    // 添加新的查询参数(示例参数,可按需替换)
    queryParams.Add("IsValid", "true");
    queryParams.Add("UserId", "123");
    
    // 更新查询字符串
    uriBuilder.Query = queryParams.ToString();
    
    // 构建最终URL并执行重定向
    string newUrl = uriBuilder.ToString();
    Response.Redirect(newUrl); // 临时重定向,需永久重定向可改用Response.RedirectPermanent(newUrl)
}

方法二:ASP.NET Core环境

ASP.NET Core中使用QueryHelpers处理查询参数,代码如下:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.WebUtilities;

public IActionResult RedirectWithAddedParams()
{
    // 原URL
    string originalUrl = "http://localhost/somesite/index.php?Filename=somefile.txt&Filepath=E:\\myfolder";
    
    // 解析原URL
    Uri uri = new Uri(originalUrl);
    
    // 读取现有查询参数并转为可修改字典
    var queryParams = QueryHelpers.ParseQuery(uri.Query);
    var mutableParams = new Dictionary<string, string>(queryParams.Count);
    foreach (var param in queryParams)
    {
        mutableParams[param.Key] = param.Value;
    }
    
    // 添加新参数
    mutableParams["IsValid"] = "true";
    mutableParams["UserId"] = "123";
    
    // 构建新URL
    string newUrl = QueryHelpers.AddQueryString($"{uri.Scheme}://{uri.Host}{uri.AbsolutePath}", mutableParams);
    
    // 执行重定向
    return Redirect(newUrl); // 临时重定向,永久重定向用RedirectPermanent(newUrl)
}

注意事项

  • 不要手动拼接URL和参数,框架工具类会自动处理特殊字符编码,避免生成无效URL。
  • 根据业务场景选择临时重定向(HTTP 302)或永久重定向(HTTP 301)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:22:37