標籤:c style class blog a http
Web API 1:
需要環境(VS2010/.Net4.0/MVC4 )
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
Web API 2:
需要環境(VS2012or2013/.Net4.5/MVC5)
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
在一步步跟著執行個體編寫代碼的過程中所遇到的問題和需要注意的地方:
1.Web API 2需通過Nuget更新Microsoft.AspNet.WebApi,否則IHttpActionResult等新增的介面無法識別。
PM> Install-Package Microsoft.AspNet.WebApi即可。
2.不同瀏覽器預設返回的資料格式不定。
IE 和 FF 由於發送了不同的Request Header的 Accept 頭,所以 web API 在響應時就發送了不同的內容類型。
比如直接存取http://localhost:8382/api/products/1
(1)Firefox返回的是xml
<Product><Category>Groceries</Category><Id>1</Id><Name>Tomato Soup</Name><Price>1</Price></Product>
accept頭:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
(2)IE返回的是json,彈出【檔案下載】對話方塊。
{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0}
accept頭:image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms- xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
如果需要統一Web API 只返回Json, 可以參考:
(1)http://www.cnblogs.com/acles/archive/2013/06/21/3147667.html
(2)http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/
(3)http://www.strathweb.com/2012/07/everything-you-want-to-know-about-asp-net-web-api-content-negotation/
3.在使用Fiddler 時,IE下無法識別localhost
需通過http://localhost.:8382/api/products 來訪問,即localhost 後面加上一個「小數點」。