开发者

How to utilize a REST API in ASP.Net 3.5?

开发者 https://www.devze.com 2023-01-28 10:32 出处:网络
I have been given some basic documentation of the RazorGator REST API and need to incorporate it into an ASP.NET 3.5 site.I\'ve created my class file to call the API which contains my WebRequest.Creat

I have been given some basic documentation of the RazorGator REST API and need to incorporate it into an ASP.NET 3.5 site. I've created my class file to call the API which contains my WebRequest.Create ("URL TO API"). How do I then make the output available so that it can be consumed by other pages? That is, the tickets.aspx page needs to obtain the output results of this API call. What constructs should I use to make this available in tickets.aspx?

Thanks!

Edit Here's the code I've written thus far:

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();

}

}

I receive the error message:

A f开发者_开发技巧ield initializer cannot reference the nonstatic field, method, or property 'field'

in the second line of the above codeblock. I'm very new to using HttpWebRequest and HttpWebResponse. Can you advise me as to how to rectify the error message I'm receiving?

Thanks!


I would create a simple class, e.g "RazorGatorResult.cs", that holds onto the different information returned from the API. (or more specifically, only the info you need).

You can then create a "RazorGatorService" assembly in your application, which the web application has a reference to.

The "RazorGatorService" would be responsible for calling the API, and hydrating the raw HTTP response (be it HTML, JSON, XML, etc) into a strongly-typed "RazorGatorResult" object, which can be used by the web tier.

Then any page can simply call through that service:

using RazorGatorService; 

RazorGatorResult result = RazorGatorService.GetSomeFunkyStuff();

This has 3 benefits:

1 - You can call the API anywhere from your web application

2 - The actual implementation (HTTP call, de-serialization) is abstracted away

3 - You can maintain/fine-tune the code in a seperate assembly, and not affect your web tier.

0

精彩评论

暂无评论...
验证码 换一张
取 消