初試Web API

來源:互聯網
上載者:User

標籤: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 後面加上一個「小數點」。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.