文本域换行内容无法通过QueryString传递至下一页的C#技术问题
解决文本域换行内容通过QueryString传递异常的问题
问题原因
直接将包含换行符的文本拼接进URL时,换行符(\r\n或\n)属于URL非法字符,会导致参数被截断或解析错误,无法正常传递到下一页。
解决方案
对所有包含换行或特殊字符的文本参数进行URL编码,接收页面再解码还原原始内容。
步骤1:修改传递端代码(编码参数)
使用HttpUtility.UrlEncode(.NET Framework)或WebUtility.UrlEncode(.NET Core/.NET 5+)对文本参数编码,确保特殊字符(包括换行)被转义为URL可识别格式。
修改后的代码示例:
// 引用命名空间:.NET Framework用using System.Web; .NET Core用using System.Net; string encodedSource = HttpUtility.UrlEncode(txtsource.Text); string encodedCase = HttpUtility.UrlEncode(txtcassee.Text); // 对所有detail文本参数编码 string encodedDetail1 = HttpUtility.UrlEncode(txt_ddetail1.InnerText); string encodedDetail2 = HttpUtility.UrlEncode(txt_ddetail2.InnerText); string encodedDetail3 = HttpUtility.UrlEncode(txt_ddetail3.InnerText); string encodedDetail4 = HttpUtility.UrlEncode(txt_ddetail4.InnerText); string encodedDetail5 = HttpUtility.UrlEncode(txt_ddetail5.InnerText); string encodedDetail6 = HttpUtility.UrlEncode(txt_ddetail6.InnerText); string encodedDetail7 = HttpUtility.UrlEncode(txt_ddetail7.InnerText); string encodedDetail8 = HttpUtility.UrlEncode(txt_ddetail8.InnerText); string encodedDetail9 = HttpUtility.UrlEncode(txt_ddetail9.InnerText); string encodedDetail10 = HttpUtility.UrlEncode(txt_ddetail10.InnerText); // 拼接编码后的URL并跳转 Response.Redirect($"adddefectdata.aspx?id={encodedSource}&score={txtscore.Text}&case={encodedCase}" + $"&hd0={Convert.ToDouble(txt_diagnosis.Value)}&hd1={Convert.ToDouble(txt_probing.Value)}" + $"&hd2={Convert.ToDouble(txt_solution.Value)}&hd3={Convert.ToDouble(txt_empathy.Value)}" + $"&hd4={Convert.ToDouble(txt_response.Value)}&hd5={Convert.ToDouble(txt_categorization.Value)}" + $"&hd6={Convert.ToDouble(txt_value.Value)}&hd7={Convert.ToDouble(txt_presentations.Value)}" + $"&hd8={Convert.ToInt32(txt_language.Value)}&hd9={Convert.ToDouble(txt_actions.Value)}" + $"&detail1={encodedDetail1}&detail2={encodedDetail2}&detail3={encodedDetail3}" + $"&detail4={encodedDetail4}&detail5={encodedDetail5}&detail6={encodedDetail6}" + $"&detail7={encodedDetail7}&detail8={encodedDetail8}&detail9={encodedDetail9}" + $"&detail10={encodedDetail10}");
步骤2:修改接收端代码(解码参数)
在adddefectdata.aspx的页面加载方法中,使用对应解码方法还原原始内容:
// .NET Framework用HttpUtility.UrlDecode,.NET Core用WebUtility.UrlDecode string source = HttpUtility.UrlDecode(Request.QueryString["id"]); string caseContent = HttpUtility.UrlDecode(Request.QueryString["case"]); string detail1 = HttpUtility.UrlDecode(Request.QueryString["detail1"]); // 其他detail参数同理解码
注意事项
- 命名空间差异:.NET Framework需引用
System.Web程序集;.NET Core/.NET 5+使用System.Net下的WebUtility类。 - 参数长度限制:QueryString有浏览器长度限制(通常约2048字符),如果文本内容过长,建议改用Session或Post请求传递。
- 数字参数:数字类型参数无需编码,直接拼接即可,但建议做好格式校验避免转换异常。
内容的提问来源于stack exchange,提问作者peermohamed s
相关产品推荐
相关产品推荐

