标签: restsharp

RestSharp ASYNC client.ExecuteAsync <T>()的示例有效

有人可以帮我修改下面的代码:

client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});
Run Code Online (Sandbox Code Playgroud)

基本上我想使用上面的ExecuteAsync方法但不想打印但返回给调用者的response.Content.

有没有简单的方法来实现这一目标?

我尝试了这个,但没有"工作:

    public T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient();
            client.BaseUrl = BaseUrl;
            client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request
            var response = client.ExecuteAsync(request, response => {
    return response.data);
});
Run Code Online (Sandbox Code Playgroud)

}

以上代码来自 https://github.com/restsharp/RestSharp

c# restsharp

18
推荐指数
2
解决办法
2万
查看次数

使用RestSharp将GET参数添加到POST请求

我想对这样的URL发出POST请求:

http://localhost/resource?auth_token=1234
Run Code Online (Sandbox Code Playgroud)

我想在体内发送JSON.我的代码看起来像这样:

var client = new RestClient("http://localhost");
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234");    
request.AddBody(json);
var response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

如何将auth_token参数设置为GET参数并将请求设置为POST?

.net c# web-services webservice-client restsharp

17
推荐指数
2
解决办法
3万
查看次数

使用RestSharp时如何以惯用方式处理HTTP错误代码?

我正在使用RestSharp构建HTTP API客户端,我注意到当服务器返回HTTP错误代码(401 Unauthorized,404 Not Found,500 Internal Server Error等)时,RestClient.Execute()不会抛出异常 - 而是我得到一个RestResponsenull .Data属性的有效.我不想在我的API客户端中手动检查每个可能的HTTP错误代码 - RestSharp是否提供了将这些错误传递给我的客户端应用程序的更好方法?

更进一步的细节.RestSharp公开一个Response.ErrorException属性 - 如果RestClient.Execute<T>()调用导致任何异常,它将通过ErrorException属性公开而不是被抛出.他们的文档包括以下示例:

// TwilioApi.cs
public class TwilioApi {
    const string BaseUrl = "https://api.twilio.com/2008-08-01";

    public T Execute<T>(RestRequest request) where T : new()
    {
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request
    var response = client.Execute<T>(request);

    if (response.ErrorException != null)
    {
        const string message …
Run Code Online (Sandbox Code Playgroud)

c# http restsharp

17
推荐指数
3
解决办法
1万
查看次数

使用Stream的RestSharp AddFile

我正在使用RestSharp(Visual Studio 2013中的版本105.2.3.0,.net 4.5)来调用NodeJS托管的Web服务.我需要做的一个调用是上传文件.使用RESTSharp请求,如果我从我的端部检索流到字节数组并将其传递给AddFile,它工作正常.但是,我更倾向于流内容而不是在服务器内存中加载整个文件(文件可以是100的MB).

如果我设置一个动作来复制我的流(见下文),我在System.Net.ProtocolViolationException的"MyStream.CopyTo"行中得到一个异常(要写入流的字节超过指定的Content-Length字节大小) .在调用client.Execute之后,在Action块中抛出此异常.

根据我的阅读,我不应该手动添加Content-Length标头,如果我这样做,它也无济于事.我已经尝试将CopyTo缓冲区设置为小值和大值,以及完全省略它,但无济于事.有人能给我一些我错过的暗示吗?

    // Snippet...
    protected T PostFile<T>(string Resource, string FieldName, string FileName,
        string ContentType, Stream MyStream, 
        IEnumerable<Parameter> Parameters = null) where T : new()
    {
        RestRequest request = new RestRequest(Resource);
        request.Method = Method.POST;

        if (Parameters != null)
        {
            // Note:  parameters are all UrlSegment values
            request.Parameters.AddRange(Parameters);
        }

        // _url, _username and _password are defined configuration variables
        RestClient client = new RestClient(_url);
        if (!string.IsNullOrEmpty(_username))
        {
            client.Authenticator = new HttpBasicAuthenticator(_username, _password);
        }

        /*
        // Does not work, …
Run Code Online (Sandbox Code Playgroud)

streaming upload restsharp

17
推荐指数
1
解决办法
1万
查看次数

RestSharp是否覆盖手动设置Content-Type?

我正在创建一个RestSharp.RestRequest:

RestRequest request = new RestRequest();
request.Method = Method.POST;
request.Resource = "/rest-uri";

request.AddHeader("Content-Type", "application/someContentType");

string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + Environment.NewLine +
             "<register-request">" + Environment.NewLine +
             "    <name=\"someName\"/>" + Environment.NewLine +
             "</register-request>");

request.AddParameter("text/xml", registerSinkRequest, ParameterType.RequestBody);
Run Code Online (Sandbox Code Playgroud)

(内容类型手动设置为application/someContentType)

在调试模式下,它也显示 Content-Type=application/someContentType

但是执行RestRequest会返回415 Media Not Supported-Error,而WireShark会显示Media-Type设置为text/xml(与AddParameter-Method中的set 一样).

为什么RestSharp显示与WireShark不同的Content-Type?如何防止更改Content-Type(如果是)?

c# restsharp

16
推荐指数
1
解决办法
1万
查看次数

使用RestSharp进行NTLM身份验证?

我正在尝试使用NTSM身份验证来使用RestSharp对TeamCity进行REST调用.

IRestClient _client=new RestClient(_url);
_client.Authenticator = new NtlmAuthenticator            
(System.Net.CredentialCache.DefaultNetworkCredentials);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.如果我错过了什么,请建议.

ntlm restsharp teamcity-7.1

16
推荐指数
4
解决办法
1万
查看次数

RestSharp HttpBasicAuthentication - 示例

我有一个使用RestSharp和WEB API服务的WPF客户端.我尝试使用HttpBasicAuthenticator如下:

RestRequest login = new RestRequest("/api/users/login", Method.POST);
var authenticator = new HttpBasicAuthenticator("admin","22");
authenticator.Authenticate(Client, login);
IRestResponse response = Client.Execute(login); 
Run Code Online (Sandbox Code Playgroud)

POST请求如下所示:

POST http://localhost/api/users/login HTTP/1.1
Authorization: Basic YWRtaW46MjI=
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.1.0.0
Host: dellnote:810
Content-Length: 0
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Run Code Online (Sandbox Code Playgroud)
  1. 如何Authorization: Basic YWRtaW46MjI=在服务器端处理此字段?我从这个标题中获取用户名和密码吗?
  2. 如何将安全令牌从服务器返回到客户端并将其保存在客户端?

我需要基于安全令牌进行简单的身份验证,但找不到描述此过程所有方面的示例.有人能指出我的一些完整的例子,包括客户端和服务器端(并使用RestSharp).

c# authentication restsharp

16
推荐指数
4
解决办法
3万
查看次数

RestSharp:如何跳过将空值序列化为JSON?

RestSharp的内置JSON序列化程序序列化了对象的所有属性,即使它们为null或者是默认值.如何让它跳过这些属性?

serialization json restsharp

15
推荐指数
3
解决办法
6446
查看次数

401仅在特定计算机上调用Web Service时

我们使用C#开发了一个WPF应用程序,并使用RestSharp与一个简单的Web服务进行通信,如下所示:

Client = new RestClient(serviceUri.AbsoluteUri);
Client.Authenticator = new NtlmAuthenticator(SvcUserName, SvcPassword.GetString());
Run Code Online (Sandbox Code Playgroud)

这一切都很有效,直到我们收到一些电话(大多数工作)的应用程序无法连接到服务.用fiddler直接调用服务方法.然后我们提取了一个小的.net控制台应用程序并尝试使用RestSharp进行服务调用并直接使用HttpWebRequest,然后再次使用401失败.现在我们启用了System.Net跟踪并注意到了一些事情.在第一个401,这是正常的,故障机器产生这个日志:

System.Net信息:0:[4480]连接#3741682 - 收到的标题{连接:保持活动内容长度:1293内容类型:text/html日期:星期一,10八月2015 12:37:49 GMT服务器:Microsoft -IIS/8.0 WWW-Authenticate:Negotiate,NTLM X-Powered-By:ASP.NET}.System.Net信息:0:[4480] ConnectStream#39451090 :: ConnectStream(缓冲1293字节.)System.Net信息:0:[4480]将HttpWebRequest#2383799与ConnectStream相关联#39451090 System.Net信息:0:[4480]将HttpWebRequest#2383799与HttpWebResponse相关联#19515494 System.Net信息:0:[4480]枚举安全包:System.Net信息:0:[4480]协商System.Net信息:0:[4480] NegoExtender System.Net信息:0 :[4480] Kerberos System.Net信息:0:[4480] NTLM系统.

System.Net信息:0:[4480] AcquireCredentialsHandle(package = NTLM,intent = Outbound,authdata = (string.empty)\ corp\svc_account)

System.Net信息:0:[4480] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY,context =(null),targetName = HTTP/mysvc.mycorp.com,inFlags = Delegate,MutualAuth,Connection)System.Net Information:0 :[4480] InitializeSecurityContext(In-Buffers count = 1,Out-Buffer length = 40,返回代码= ContinueNeeded).

工作机器产生这样的输出:

System.Net信息:0:[3432]连接#57733168 - Empfangene Statusleiste:Version = 1.1,StatusCode = 401,StatusDescription = Unauthorized.System.Net信息:0:[3432]连接#57733168 - 标题{Content-Type:text/html服务器:Microsoft-IIS/8.0 WWW-Authenticate:Negotiate,NTLM X-Powered-By:ASP.NET Date:Mon, 2015年8月10日15:15:11 GMT内容长度:1293} wurden empfangen.System.Net信息:0:[3432] ConnectStream#35016340 :: …

c# ntlm httpwebrequest restsharp http-status-code-401

15
推荐指数
1
解决办法
593
查看次数

如何将json添加到RestSharp POST请求中

我有以下JSON字符串作为字符串参数传递给我的c#代码 - AddLocation(string locationJSON):

{"accountId":"57abb4d6aad4","address":{"city":"TEST","country":"TEST","postalCode":"TEST","state":"TEST","street":"TEST"},"alternateEmails":[{"email":"TEST"}],"alternatePhoneNumbers":[{"phoneNumber":"TEST"}],"alternateWebsites":[{"website":"TEST"}],"auditOnly":false,"busName":"593163b7-a465-43ea-b8fb-e5b967d9690c","email":"TEST EMAIL","primaryKeyword":"TEST","primaryPhone":"TEST","rankingKeywords":[{"keyword":"TEST","localArea":"TEST"}],"resellerLocationId":"5461caf7-f52f-4c2b-9089-2ir8hgdy62","website":"TEST"}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将JSON添加到这样的RestSharp POST请求中,但它不起作用:

public string AddLocation(string locationJSON)
{
    var client = new RestClient(_authorizationDataProvider.LocationURL);
    var request = new RestRequest(Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("Authorization", _authorizationResponse.Token);
    ...
    request.AddJsonBody(locationJSON);
    var response = client.Execute(request);
}
Run Code Online (Sandbox Code Playgroud)

响应回复为"错误请求".如果我在调试器中检查响应,这是我得到的:

{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}}
Run Code Online (Sandbox Code Playgroud)

我在调用AddJsonBody之后检查了请求参数,并且值似乎包括双引号的转义序列 - 这似乎是个问题.

{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何将json字符串添加到请求体?

c# json restsharp

15
推荐指数
2
解决办法
2万
查看次数