2010-11-29 110 views
0

我已經給出了RazorGator REST API的一些基本文檔,並且需要將它合併到ASP.NET 3.5網站中。我創建了我的類文件來調用包含我的WebRequest.Create(「URL TO API」)的API。那麼如何讓輸出可用,以便其他頁面可以使用呢?也就是說,tickets.aspx頁面需要獲取此API調用的輸出結果。我應該使用什麼構造來使ticket.aspx中可用?如何在ASP.Net 3.5中使用REST API?

謝謝!

編輯 下面是我迄今爲止編寫的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.IO; 
using System.Net; 
using System.Text; 

namespace SeatEater.Web.UI.search 
{ 
public class RazorGatorService 
{ 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.razorgator.com/ticketservice/ticets.xml?blahblah") as HttpWebRequest ; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream receiveStream = response.GetResponseStream(); 
    StreamReader readStream = new StreamReader(receiveStream, encode); 
    response.close(); 
    readStream.close(); 

} 

} 

我收到錯誤消息:

A field initializer cannot reference the nonstatic field, method, or property 'field' 

在上面的代碼塊的第二行。我很新使用HttpWebRequest和HttpWebResponse。你能否告訴我如何糾正我收到的錯誤信息?

謝謝!

回答

4

我會創建一個簡單的類,例如「RazorGatorResult.cs」,它保存從API返回的不同信息。 (或者更具體地說,只有你需要的信息)。

然後,您可以在應用程序中創建一個「RazorGatorService」程序集,Web應用程序可以引用該程序集。

的「RazorGatorService」將負責調用API,以及水合所述經原始HTTP響應(無論是HTML,JSON,XML等)轉換成一個強類型「RazorGatorResult」對象,其可以是由Web層使用。

那麼任何頁面可以通過該服務只需撥打:

using RazorGatorService; 

RazorGatorResult result = RazorGatorService.GetSomeFunkyStuff(); 

這有3個好處:

1 - 你可以從你的web應用程序

2隨時隨地調用API - 實際實現(HTTP調用,反序列化)被抽象出來

3 - 您可以在單獨的程序集中維護/微調代碼,而不會影響您的網絡層。

+0

當你說原始HTTP響應補充到一個強類型RazorGatorResult時,我會創建一個數據表來保存從API返回的XML嗎?或者,是否有另一個更適合的對象來存儲由API返回的XML? – SidC 2010-11-29 18:47:45