代码之家  ›  专栏  ›  技术社区  ›  SidC

如何在ASP.Net 3.5中使用REST API?

  •  0
  • SidC  · 技术社区  · 14 年前

    我已经获得了RazorgatorRestaPI的一些基本文档,需要将其合并到一个ASP.NET3.5站点中。我创建了类文件来调用包含我的WebRequest.Create(“URL to API”)的API。然后如何使输出可用,以便其他页面可以使用它?也就是说,tickets.aspx页面需要获取此API调用的输出结果。我应该使用什么结构来使它在tickets.aspx中可用?

    谢谢!

    编辑 这是我到目前为止写的代码:

    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非常陌生。你能告诉我如何纠正我收到的错误信息吗?

    谢谢!

    1 回复  |  直到 14 年前
        1
  •  4
  •   RPM1984    14 年前

    我会创建一个简单的类,例如“ RazorGatorResult.cs公司 ,它保存从API返回的不同信息。(或者更具体地说,只有你需要的信息)。

    然后您可以创建一个“ RazorGatorService公司 “应用程序中的程序集,web应用程序引用了它。

    “那” RazorGatorService公司 负责调用API,并将原始的HTTP响应(HTML、JSON、XML等)水合为强类型 RazorGatorResult公司 对象,可由web层使用。

    然后,任何页面都可以通过该服务调用:

    using RazorGatorService; 
    
    RazorGatorResult result = RazorGatorService.GetSomeFunkyStuff();
    

    这有三个好处:

    1-您可以在web应用程序的任何位置调用API

    3-您可以在单独的程序集中维护/微调代码,而不会影响您的web层。