一個很小很小的問題,只是以前都很鄉愿地繞路避開,今天終於肯花時間找到正解:

static void StringFormatTest(string custCode)
{
    string s = string.Format(@"
function blah() {
    {0}
}", custCode);
    Console.Write(s);
}

以上的寫法,在執行時會跑出System.FormatException: Input string was not in a correct format.(輸入字串格式不正確。)  原因很清楚,{與}在格式化表示時是用來包數字標註變數內容的位置,而它恰好與Javascript的Block符號相同,造成誤解。隨便Google了一下,用string.format+escape當關鍵字,一下就找到解答(很奇怪過去為什麼都沒花心思去找?)。在String.Format中,{{代表{、}}代表},就跟@"...."中表示雙引號要重覆打兩次一樣,That's all, folks.

static void StringFormatTest(string custCode)
{
    string s = string.Format(@"
function blah() {{
    {0}
}}", custCode);
    Console.Write(s);
}

有用的參考資料: http://blogs.msdn.com/brada/archive/2004/01/14/58851.aspx

PS: 順便做一下資安宣導,以上的寫法若custCode是由使用者自由輸入時,會有XSS的風險,相關文章: 參考1/參考2


Comments

Be the first to post a comment

Post a comment