【问题标题】:How to interact with a REST service in C# [closed]如何在 C# 中与 REST 服务交互 [关闭]
【发布时间】:2016-11-08 13:16:52
【问题描述】:

我正在开发一个必须与 JSON/REST 服务交互的小型应用程序。 在我的 c# 应用程序中与之交互的最简单的选项是什么。

我不需要最好的性能,因为它只是一个每天会做一些同步的工具,我更倾向于易用性和开发时间。

(相关服务将是我们的本地 JIRA 实例)。

【问题讨论】:

  • 这主要是基于意见并寻求框架建议。两者都是题外话。
  • ?我不问任何框架,只问怎么做
  • 你会认为是6年的会员;前 6%;约 4500 名代表会知道如何提出一个好问题
  • 你不认为“我如何与之交互”意味着要求使用框架或工具来执行交互吗?您是否认为这是基于意见的,因为您说“什么是最简单的?”您是否认为它太宽泛了,因为您的问题并不具体,并且是关于具有许多可能答案的广泛主题? Stack Overflow 用于回答特定的编程问题。选择一个框架,决定如何实现它。如果您在实现代码时遇到困难,那么您将有一个有效的话题要问。你做的够久了,为别人树立一个好榜样。
  • @mason 我只是想知道执行此操作的选项,如果有内置解决方案(如 Visual Studio 中的参考远程服务)

标签: c# json rest


【解决方案1】:

我认为目前最好的方法是使用RestSharp。这是一个免费的 Nuget 包,您可以参考。它非常易于使用,这是他们网站上的示例:

var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile(path);

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;

// easy async support
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort();

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多