2013-07-03 36 views
0

嘗試使用string.join將字符串列表連接在一起。當我使用分隔符字符串「OR」時,空白符將被替換爲正在破壞我的targetUri字符串的「+」。以下是用於加入的代碼。使用string.join時字符串空白替換錯誤

if (DocumentSearchListViewModel.Filter == null) 
     { 
      return "http://000.000.00.00:8080/value/value/search/json?terms=value%20OR%20value&target=TEST2&maxResults=5"; 
     } 

     var targetUri = "http://000.000.00.00:8080/value/value/search/json?"; 

     NameValueCollection termsString = System.Web.HttpUtility.ParseQueryString(string.Empty); 

     if (!string.IsNullOrWhiteSpace(DocumentSearchListViewModel.Filter.Keywords)) 
     { 
      if (!string.IsNullOrWhiteSpace(DocumentSearchListViewModel.Filter.Author)) 
      { 
       DocumentSearchListViewModel.Filter.Keywords += (" " + DocumentSearchListViewModel.Filter.Author); 
      } 

      IList<string> keywords = DocumentSearchListViewModel.Filter.Keywords.Split(); 

      termsString["terms"] = string.Join(" OR ", keywords);   
     }   

     targetUri += termsString.ToString(); 
     targetUri += "&target=TEST2&maxResults="; 
     targetUri += DocumentSearchListViewModel.Filter.MaxNumberOfResults ?? "5"; 

     return targetUri; 

我在Google上做了很多搜索,但一直沒能找到任何有關string.join替換字符的內容。在我的調試過程中,我能夠將其縮小到條件字符串行,作爲發生問題的位置。

這裏是字符串我出去的實際例子:條件=值1 + OR +值2 + OR + VALUE3

如何我將停止從+字符被替換的空格?

乾杯,

詹姆斯

+2

'+'被添加到URL中。您是否在代碼的其他部分對結果進行了URL編碼?如果你設置了一個斷點並檢查string.Join返回的值,我敢打賭它不包含任何'+'字符 –

+0

你如何使用'termsString [「terms」]的值? –

+1

問題不在'string.Join'中,你的關鍵字必須以某種方式包含'+',否則它會被替換。 –

回答

-1

爲了獲取URL在服務器端的解碼值,你應該使用:

var encoded = "terms=value1+OR+value2+OR+value3"; 
var decoded = System.Web.HttpUtility.UrlDecode(encoded); 

@PanagiotisKanavos,關於我以前使用%20,而不是建議請看這個JS:

var uri1="terms=value1%20OR%20value2%20OR%20value3"; 
var uri2="terms=value1+OR+value+OR+value3"; 
document.write(decodeURIComponent(uri1)); 
document.write("<br/>"); 
document.write(decodeURIComponent(uri2)); 

如果你運行它,你會發現編碼在某些情況下可能很敏感。

+0

String.Join不編碼任何東西。使用%20替換空格將導致在編碼結果時對'%'進行附加編碼。此外,'+'也是空格的有效url編碼 –

+0

我知道,我從來沒有這樣說過,但由於沒有給出使用termsString [「terms」]值的上下文,所以我提出了一個建議,可能會幫助調試。你怎麼知道沒有自定義的URL引用? –

+0

@PanagiotisKanavos,這就是爲什麼我建議在我的答案的前一個版本中使用'%20':[http://stackoverflow.com/a/1211249/674700](http://stackoverflow.com/a/ 1211249/674700)(只是爲了消除這種_picky_系統的可能性)。這是一個演示[http://jsfiddle.net/a4TnE/](http://jsfiddle.net/a4TnE/)。 –