使用参数从MVC控制器重定向到外部网址 [英] Redirect to external Url from MVC controller with parameters
问题描述
我希望通过传递变量将用户重定向到此链接
i want to redirect the user to this link with being able to pass variables
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)就会起作用
The current method I have adds the Url link to the localhost link.Which gives the error- "A potentially dangerous Request.Path value was detected from the client (:)." and the url link(google) does work once I remove the added localhost link
推荐答案
正如评论中已经提到的,需要正确构建url.
As already mentioned in the comments the url needs to be properly constructed.
首先构造并编码插入的片段.
first construct and encode the inserted segment.
var segment = string.Join(" ",address, Area, city, zipCode);
var escapedSegment = Uri.EscapeDataString(segment);
然后,您使用基本格式和转义的段来构建完整的URL
You then construct the complete URL with the base format and the escaped segment
var baseFormat = "https://www.google.co.za/maps/search/{0}/";
var url = string.Format(baseFormat, escapedSegment);
并使用它进行重定向.
完整的代码看起来像这样
Complete code would look something like this
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);
}
您甚至可以在尝试将构造的URL与 if(Uri.IsWellFormedUriString(url,UriKind.Absolute))
You could even consider validating the constructed URL before trying to use it with if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
这篇关于使用参数从MVC控制器重定向到外部网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!