Redirect to external Url from MVC controller with

2019-08-03 02:38发布

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));

        }

The View

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

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

2条回答
姐就是有狂的资本
2楼-- · 2019-08-03 03:00

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);

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);

And use that to do the redirect.

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);
}

You could even consider validating the constructed URL before trying to use it with if (Uri.IsWellFormedUriString(url, UriKind.Absolute))

查看更多
▲ chillily
3楼-- · 2019-08-03 03:23

Here is the solution for the error,"A potentially dangerous Request.Path value was detected from the client (:)"

Try these settings in webconfig file:

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

Controller code:

if you want to pass variable, give the value after the question mark like below

 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));

  }
查看更多
登录 后发表回答