gpt4 book ai didi

c# - URL 中的 URL 编码斜杠

转载 作者:IT王子 更新时间:2023-10-29 03:47:20 29 4
gpt4 key购买 nike

我的 map 是:

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with params
new { controller = "Home", action = "Index", id = "" } // Param defaults
);

如果我使用 URL http://localhost:5000/Home/About/100%2f200,则没有匹配的路由。我将 URL 更改为 http://localhost:5000/Home/About/100 然后再次匹配路由。

有什么简单的方法可以处理包含斜线的参数吗?其他转义值(空格 %20)似乎有效。

编辑:

编码 Base64 对我有用。它使 URL 变得丑陋,但现在没关系。

public class UrlEncoder
{
public string URLDecode(string decode)
{
if (decode == null) return null;
if (decode.StartsWith("="))
{
return FromBase64(decode.TrimStart('='));
}
else
{
return HttpUtility.UrlDecode( decode) ;
}
}

public string UrlEncode(string encode)
{
if (encode == null) return null;
string encoded = HttpUtility.PathEncode(encode);
if (encoded.Replace("%20", "") == encode.Replace(" ", ""))
{
return encoded;
}
else
{
return "=" + ToBase64(encode);
}
}

public string ToBase64(string encode)
{
Byte[] btByteArray = null;
UTF8Encoding encoding = new UTF8Encoding();
btByteArray = encoding.GetBytes(encode);
string sResult = System.Convert.ToBase64String(btByteArray, 0, btByteArray.Length);
sResult = sResult.Replace("+", "-").Replace("/", "_");
return sResult;
}

public string FromBase64(string decode)
{
decode = decode.Replace("-", "+").Replace("_", "/");
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(Convert.FromBase64String(decode));
}
}

编辑1:

最后证明,最好的方法是为我需要选择的每个项目保存一个格式良好的字符串。那好多了,因为现在我只对值进行编码而从不对其进行解码。所有特殊字符都变成“-”。我的很多数据库表现在都有这个附加列“URL”。数据非常稳定,这就是为什么我可以走这条路。我什至可以检查“URL”中的数据是否是唯一的。

编辑2:

还要注意空格字符。它在 VS 集成网络服务器上看起来不错,但在 iis7 上却不同 Properly url encode space character

最佳答案

如果这只是你的最后一个参数,你可以这样做:

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{*id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }); // Parameter defaults

关于c# - URL 中的 URL 编码斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/591694/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com