【问题标题】:Using A Web API for Business Logic?为业务逻辑使用 Web API?
【发布时间】:2013-01-30 03:35:33
【问题描述】:

我的 Web 应用程序需要能够从 Paymo http://api.paymo.biz/ 获取我的所有项目

我熟悉 JSON 和 XML,但我想知道的是,如何与 api 交互(对其进行调用)。

理想情况下,我想在 ASP .Net 中创建一个类,例如 PaymoManager(int apikey....)

从那里我可以包装我需要的功能。我只需要了解,如何调用 API 的函数以及如何获得响应。我对 web api 不熟悉。


编辑:你能给我一个例子,即使是一些抽象的网址。我需要在 CS 文件中完成服务器端。

基本上是一个简单的例子,它调用 someurl.com/somerequest,然后你如何接收 JSON 或 XML……这在类方面是如何工作的。我想在课堂上这样做。

【问题讨论】:

  • 您调用 URL,接收 XML 并使用它。对于您要寻找的答案,我有点困惑。
  • 你能给我一个例子吗,即使是一些抽象的网址。我需要在 CS 文件中完成服务器端。
  • 基本上是一个简单的例子,它调用 someurl.com/somerequest 然后你如何接收 JSON 或 XML ......这在类方面是如何工作的。我想在课堂上这样做。
  • 您阅读过您链接到的文档吗?这似乎相当简单。按照自己的方式完成示例,如果您在某个特定问题上遇到困难,请修改您的问题以描述您尝试过的内容和无效的内容。
  • 我只想把它做好。我了解如何将网址放在一起。但是然后我如何在我的cs代码文件中发送请求并接收响应。我不想使用 javascript...

标签: c# asp.net api


【解决方案1】:

http://api.paymo.biz/docs/misc.overview.html

要使用 Paymo API 执行操作,您需要发送请求 到 Paymo 网络服务,指定一个方法和一些参数,以及 将收到格式化的响应。

这意味着您可以从 url 使用WebClient to download a string

WebClient client = new WebClient();
string reply = client.DownloadString (address);

根据您指定的格式,您可以将回复解析为XMLJSON

XDocument xml = XDocument.Parse(reply);

// where ReplyType is a class that defines public 
// properties matching the format of the json string
JavaScriptSerializer serializer = new JavaScriptSerializer();
ReplyType abc = serializer.Deserialize<ReplyType>(reply);

【讨论】:

  • 如何检查失败?这会引发某种异常吗?
【解决方案2】:

如果您使用的是 .NET 4.5,则可以考虑使用 HttpClient,如下所示:

static async void Main()
    {
    try 
    {
      // Create a New HttpClient object.
      HttpClient client = new HttpClient();

      // fill in the details in the following string with your own KEY & TOKEN:
      string requestUrl = "https://api.paymo.biz/service/paymo.auth.logout?api_key=API_KEY&format=JSON&auth_token=AUTH_TOKEN"
      HttpResponseMessage response = await client.GetAsync(requestUrl );
      response.EnsureSuccessStatusCode();
      string responseBodyJSON = await response.Content.ReadAsStringAsync();
      // Above three lines can be replaced with new helper method in following line 
      // string body = await client.GetStringAsync(uri);

      Console.WriteLine(responseBodyJSON );
      // Now you can start parsing your JSON....

    }  
    catch(HttpRequestException e)
    {
      Console.WriteLine("\nException Caught!"); 
      Console.WriteLine("Message :{0} ",e.Message);
    }
  }

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2012-07-15
    • 2017-01-02
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多