【问题标题】:Passing URL as string -- everything after '&' gets lost将 URL 作为字符串传递 - '&' 之后的所有内容都会丢失
【发布时间】:2016-07-25 14:18:01
【问题描述】:

我有一个在 onclick 事件中进行 API 调用的 MVC 应用程序

<a href="javascript://" onclick="@Model.MyApiCall"></a>

@Model.MyApiCall 是一个看起来像这样的字符串:

window.location = 'http://localhost/myPath?myImagePath=http://myimagepath&width=360&category=2'

这成功调用了我的 API。到目前为止,一切都很好。 但是,由于某种原因,& 之后的所有内容都从 myImagePath 中截断。所以不是 myImagePath 等于我点击发送的内容,我只得到这个:

http://myimagepath

【问题讨论】:

    标签: javascript c# asp.net-mvc url asp.net-web-api


    【解决方案1】:

    您必须对查询字符串参数进行编码。你可以用javascript来做:

    window.location = 'http://localhost/myPath?myImagePath=' + encodeURIComponent('http://myimagepath') + '&width=360&category=2'
    

    使用encodeURIComponent

    您也可以在 MVC 控制器中使用 HttpUtility.UrlEncode 仅在 Model.MyApiCallhttp://myimagepath 部分上执行此操作。

    [编辑]

    如果您的myImagePath 参数是整个http://myimagepath&amp;width=360&amp;category=2 字符串,那么史蒂夫·丹纳当然是对的,您应该遵循他的回答。

    【讨论】:

      【解决方案2】:

      您正在尝试将 url 作为 url 参数传递。由于有问题的 url 包含特殊字符,因此您需要对 uri 组件进行转义/编码。

      由于您使用的是 ASP.Net,因此您应该使用以下内容包装字符串:

      window.location = Uri.EscapeUriString('http://localhost/myPathmyImagePath=http://myimagepath&width=360&category=2')
      

      【讨论】:

        【解决方案3】:

        和号 (&) 是一个特殊字符,需要进行编码才能被浏览器正确解析。您需要将查询字符串和实际路径分解为单独的字符串。像这样的:

        <a href="javascript://" onclick="@(Model.MyApiCallPath +
         HttpUtility.UrlEncode(Model.MyApiCallQueryString))"></a>
        

        您的最终 js 将如下所示:

        window.location = 'http://localhost/myPath?myImagePath=http%3A%2F%2Fmyimagepath%26width%3D360%26category%3D2';
        

        【讨论】:

        • 谢谢,这正是我需要的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-01
        • 1970-01-01
        • 2019-12-11
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        相关资源
        最近更新 更多