2017-06-29 109 views
1

我希望用戶把這個鏈接重定向以能夠傳遞變量從MVC控制器參數

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

     } 

的視圖重定向到外部URL

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

目前的方法,我有添加Url鏈接到本地​​主機鏈接。其中給出錯誤 - 「從客戶端(:)發現潛在危險的Request.Path值。」 和URL鏈接(谷歌)一旦予除去添加的本地主機鏈路

+2

使用它,因爲你是手動生成的URL之前驗證構造的URL,你需要使用' Url.Encode(地址+區域+城市+ zipCode)' – haim770

+0

您需要在連接地址後使用'Response.Redirect(url)' – Monah

+0

爲什麼當客戶端已經擁有所需的所有信息時只發出一個JS重定向? –

回答

0

正如已經在評論中提到的那樣,url需要被正確構建。

首先構造並編碼插入的段。

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

完整的URL並用它來執行重定向。

完整代碼會是這個樣子

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

+0

您能解釋爲什麼以前的代碼不工作,因爲我嘗試Url.Ecode作爲var encode = HttpUtility.UrlEncode(地址+區域+城市+ zipCode)並將其傳遞到string.format.As結果是「https: //www.google.co.za/maps/search/49+Biston ...「,並且這個網址也被添加了我的本地主機。至於你的回答是」https://www.google.co.za/maps/搜索/ 49%20Biston ...「,並沒有被添加到本地主機網址,該網址按預期打開 –

0

這裏確實工作是錯誤的解決方案,「從客戶端檢測到有潛在危險的Request的值(:)」

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

    }