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

ASP.NET中如何在两个Web项目间传递变量?

跨Web项目重定向并传递字符串变量的解决方案

一、先解决跨项目重定向的核心问题

你原来用的~/是当前项目根路径的相对标识,只能指向WebApplication1内部的资源,跨项目必须用目标项目的正确路径:

  • 如果两个项目部署在同一服务器的同一站点下(比如IIS里是两个子应用),直接用站点根相对路径:/WebApplication2/TestRedirect.aspx
  • 如果是独立站点/不同服务器,必须用完整的绝对URL:http://你的WebApplication2域名/TestRedirect.aspx

二、传递字符串变量的可行方案

方案1:QueryString(简单直接,适合非敏感数据)

这是最常用的方式,把变量拼在URL的查询参数里,注意要对特殊字符编码避免错误:

// 发送方(WebApplication1)代码
string send = "你的数据库获取到的字符串";
// 编码后拼接参数,参数名自定义(比如叫data)
string targetUrl = "/WebApplication2/TestRedirect.aspx?data=" + HttpUtility.UrlEncode(send);
Response.Redirect(targetUrl);

接收方(WebApplication2的TestRedirect.aspx后台)获取:

string receivedData = Request.QueryString["data"];
// 记得判断是否为null
if (!string.IsNullOrEmpty(receivedData))
{
    // 处理数据
}

方案2:Post表单提交(适合敏感数据,避免URL暴露)

如果字符串包含敏感信息,用Post方式更安全,通过动态生成表单自动提交:

// 发送方(WebApplication1)代码
string send = "你的敏感字符串";
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><body>");
// 目标地址换成你的WebApplication2页面路径
htmlBuilder.Append($"<form id='postForm' action='/WebApplication2/TestRedirect.aspx' method='POST'>");
htmlBuilder.Append($"<input type='hidden' name='data' value='{HttpUtility.HtmlEncode(send)}' />");
htmlBuilder.Append("</form>");
htmlBuilder.Append("<script>document.getElementById('postForm').submit();</script>");
htmlBuilder.Append("</body></html>");

Response.Clear();
Response.Write(htmlBuilder.ToString());
Response.End();

接收方(WebApplication2的TestRedirect.aspx后台)获取:

string receivedData = Request.Form["data"];

方案3:共享Session(适合多数据传递,配置稍复杂)

如果需要传递多个变量或者保持会话状态,可配置两个项目共享Session:

  1. 两个项目的web.config中配置相同的machineKey(确保加密一致):
<system.web>
    <machineKey validationKey="你的固定密钥" decryptionKey="你的固定密钥" validation="SHA1" decryption="AES" />
    <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" timeout="20" />
</system.web>
  1. 启动ASP.NET State Service服务(Windows服务中查找)
  2. 发送方存Session:
Session["SharedData"] = send;
Response.Redirect("/WebApplication2/TestRedirect.aspx");
  1. 接收方取Session:
string receivedData = Session["SharedData"]?.ToString();

三、排查你原来代码的问题

你之前的代码Response.Redirect("~/WebApplication2/TestRedirect.aspx" + send)有两个明显问题:

  • 用了~/导致路径解析错误,无法指向跨项目资源
  • 直接拼接变量,没有加参数名(比如?data=),就算路径正确,接收方也无法识别变量

内容的提问来源于stack exchange,提问作者Imran Canlı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:32:09