【问题标题】:Redirect to external Url from MVC controller with parameters使用参数从 MVC 控制器重定向到外部 URL
【发布时间】:2017-06-29 17:20:27
【问题描述】:

我想通过能够传递变量将用户重定向到此链接

    public ActionResult GoogleMapAddress(string address, string Area, string city, string zipCode)
        {

           return Redirect(string.Format(" https://www.google.co.za/maps/search/{0}/ ", address + Area + city + zipCode));

        }

观点

@Html.ActionLink("Address", "GoogleMapAddress", "Orders", new { address="test", Area="test", city="test", zipCode="test" },new  {target="_blank" })

我将Url链接添加到localhost链接的当前方法。这给出了错误- “从客户端 (:) 检测到潜在危险的 Request.Path 值。” 一旦我删除添加的 localhost 链接,url 链接(google)就可以工作

【问题讨论】:

  • 由于是手动生成url,所以需要使用Url.Encode(address + Area + city + zipCode)
  • 连接地址后需要使用Response.Redirect(url)
  • 当客户端已经拥有发出 js 重定向所需的所有信息时,为什么还要进行服务器调用?

标签: c# asp.net-mvc url


【解决方案1】:

正如 cmets 中已经提到的,需要正确构建 url。

首先构造并编码插入的片段。

var segment = string.Join(" ",address, Area, city, zipCode);
var escapedSegment = Uri.EscapeDataString(segment);

然后您使用基本格式和转义段构造完整的 URL

var baseFormat = "https://www.google.co.za/maps/search/{0}/";
var url = string.Format(baseFormat, escapedSegment);

然后用它来做重定向。

完整的代码如下所示

public ActionResult GoogleMapAddress(string address, string Area, string city, string zipCode) {
    var segment = string.Join(" ",address, Area, city, zipCode);
    var escapedSegment = Uri.EscapeDataString(segment);
    var baseFormat = "https://www.google.co.za/maps/search/{0}/";
    var url = string.Format(baseFormat, escapedSegment);
    return Redirect(url);
}

您甚至可以考虑在尝试将其与if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) 一起使用之前验证构造的 URL

【讨论】:

  • 你能解释一下为什么前面的代码不起作用,因为我尝试 Url.Ecode as var encode = HttpUtility.UrlEncode(address + Area + city + zipCode) 并以 string.format 传递它。因为结果是“google.co.za/maps/search/49+Biston...”,这个 url 也被添加到我的 localhost。因为你的答案是“google.co.za/maps/search/49%20Biston...”并且没有被添加到 localhost url,它按预期打开
【解决方案2】:

这里是错误的解决方案,“从客户端检测到潜在危险的 Request.Path 值 (:)”

在 webconfig 文件中尝试这些设置:

<system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>

控制器代码:

如果要传递变量,请在问号后面给出值,如下所示

 public ActionResult GoogleMapAddress(string address, string Area, string city, string zipCode)
        {

           return Redirect(string.Format(" https://www.google.co.za/maps/search/{0}?inparam1="somevalue" ", address + Area + city + zipCode));

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-31
    • 2010-12-05
    • 2019-01-14
    • 1970-01-01
    • 2012-04-02
    • 2021-07-23
    • 2016-03-27
    • 1970-01-01
    相关资源
    最近更新 更多