如何使用路由傳遞含"+"符號到Web API 2

Web API 2如何使用路由傳遞"+"符號

我們需要傳遞一個加密過的參數,此加密方法產生有一定機會產出含"+"符號的亂數。"+"符號在網路傳遞過程中會有一些問題,常見的解決辦法是傳遞前後使用Encode與Decode方法來針對特殊符號進行加解密。但在Web API 2比較難處理。

Web API 2與"+"號的邂逅

在預設的Web API 2範本及預設的路由"api/{controller}/{id}"設置下,簡單進行兩個測試:

測試一

以QueryString方式"/api/values?id=1%2b1"進行請求。這裡的%2b是"+"符號Encode的代表號。這個測試可以順利到達Get(string id)方法之內。

測試二

以ASP.NET MVC Route的方式"/api/values/1%2b1"進行請求。接來來會爆一個Http 404錯誤頁面。

另外參考這裡,將%2b進行二次加密,可以得到"%252b",拿來進行請求"/api/values/%252b"依然是Http 404。

解決Web API路由傳遞+符號

其實解決辦法很簡單,但我不死心,寫信去問開發組(OpenSource的好處之一),但我們先看來一下ASP.NET團隊的正式說明:(是@danroth27本人回信,超高興的)

The Request Filtering module is rejecting the request before it ever makes it to Web API. Setting allowDoubleEscaping to true is the only way I know to work around this.

You can find further details on what Request Filtering does here:http://blogs.iis.net/nazim/use-of-special-characters-like-in-an-iis-url

Layer 2: IIS request filtering (blocked characters = ‘%25’, ‘.’, ‘%2b’)

IIS request filtering checks for a couple of things by default and the behavior is controlled by configuration. You can reference the following articles for details, Use Request Filtering and Using Urlscan. This filtering potentially processes both the URI path and the query string and could disallow things like:

  1. Double escaping which involves the use of %25, which is an encoded ‘%’ sign. Also, ‘+’ characters are considered and encoded space even though it does not have a % in the beginning. So encoding this as %2b will also trigger this rule.
  2. Non-ASCII high bit characters.
  3. Dot in the URI path, where a request that contains a dot other than that for the resource extension will be rejected. Eg: http://foo/a.b/bar.aspx
Daniel Roth

allowDoubleEscaping是唯一的解決辦法:

 <system.webServer>
     <security>
         <requestFiltering allowDoubleEscaping="true"/>
     </security>
 </system.webServer>  
 

請注意,開啟allowDoubleEscaping設置會減低系統安全性。最後覺得這個情境下既然QueryString能解決我們的問題又不會減低系統安全性的疑慮,最後我們還是走QueryString來傳遞這個含"+"符號的字串。

更好的解法請參考:如何於MVC/Web API路由中傳送Base64編碼

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。