c# - URL 中的 URL 编码斜杠

标签 c# asp.net-mvc asp.net-mvc-routing urlencode

我的 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/

相关文章:

c# - ASP.NET MVC Ajax 中的 500 内部错误

asp.net-mvc - ASP.NET MVC5 表单值未绑定(bind)到模型

asp.net-mvc - 我应该为每个模型创建一个接口(interface)吗?

Asp.NET MVC 2 路由

ASP.NET MVC 默认 URL View

c# - MySql语句准备 "not sticking"

c# - ASP.NET Massive - 如何创建数据库以显示 VIEW

c# - 由于线程退出或应用程序请求,I/O 操作已中止

asp.net-mvc-routing - ASP.NET MVC 6 中默认 url 的路由错误

c# - ASP.NET 核心 DI : Resolve same instance if scoped service is registered both as service type and implementation type