最近在處理專案中所有功能紀錄的串接,
因此在web專案Call Api專案時,
需要帶入固定的登入者相關UserInfo資料
◆筆記1 [FromUri]
//ApiController
public IHttpActionResult Get([FromUri]<T model>);
同事在某隻API參數 放上了"[FromUri]"屬性,
整個專案中幾乎都是post方法,在這呼叫api就出事了
GET方法如果要透過URI傳遞參數,除非標記上[FromUri]屬性,又或者是其為SimpleType ,因為GET/POST方法會告訴API傳遞與接收的範圍為何(參考1.2)
◆筆記2 UriBuilder QueryString編碼問題
當上述UserInfo資料透過 requestParameter加入時,
因為Value為中文,在API端收到的資料全都變成了亂碼
處理了編碼問題,<T model>就可以收到正確的參數了
UriBuilder uriBuilder = new UriBuilder(ServiceURL);
NameValueCollection requestParameter = HttpUtility.ParseQueryString(string.Empty);
//加入UserInfo相關參數
requestParameter.Add(propertyName ,propertyValue)
if (requestParameter.Count > 0)
{
//原來的Code
uriBuilder.Query = requestParameter .ToString();
//修改為
uriBuilder.Query=HttpUtility.UrlDecode(requestParameter .ToString(), Encoding.UTF8);//將參數轉為 QueryString
ServiceURL = uriBuilder.Uri; //更新 ServiceURL, 將 QureyParams 包括進網址中
}
參考1
Parameter binding Default rule :
.Simple types are taken from the URI.
.Complex types are taken from the request
參考2
根據協定關於Message Body的規則(standard defintion Hypertext Transfer Protocol 4.3 )
The rules for when a message-body is allowed in a message differ for requests and responses.
The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.
參考資料來源: https://stackoverflow.com/questions/16927862/why-do-i-have-to-specify-fromuri-to-get-this-to-work