标签: restsharp

如何将 json 格式的有效负载附加到 RestSharp 请求中?

我不能在 RestSharp 的请求中放置工作负载。谁能帮我?

我测试过

request.AddBody(payload) -> 有效载荷是 json 中的序列化对象

但是,对我不起作用:

public override string Post(string url, object payload) { 
    RestRequest request = new RestRequest(url, Method.POST); 
    request.RequestFormat = DataFormat.Json;
    request.AddBody(payload); 
    IRestResponse response = Client.Execute(request); 
    return response.Content; 
} 
Run Code Online (Sandbox Code Playgroud)

方法的返回是空字符串 :/ :/

c# request payload restsharp oauth-2.0

2
推荐指数
1
解决办法
4133
查看次数

如何处理异步函数中的返回值

在处理使用异步 rest 调用的数据 API 时(我使用的是 RestSharp.Portable),处理返回值的最佳方法是什么?由于 async 函数只能返回一个 Task 或 Task ......但调用者无法返回返回值...... API如何将数据返回给调用者?全局属性?

从我到目前为止所读到的内容来看,回调函数似乎是与响应数据交互的唯一方法?

以下面的方法为例;以前我没有使用异步 Rest 库并且能够返回一个值,但是在将其转换为使用 RestSharp.Portable 后,我没有看到返回值的方法:

public async Task<EntityResourceDescriptor> GetEntityDescriptor(string entityType)
    {
        TaskCompletionSource<EntityResourceDescriptor> tcs = new TaskCompletionSource<EntityResourceDescriptor>();
        var req = new RestRequest("/qcbin/rest/domains/{domain}/projects/{project}/customization/entities/{entityType}");
        AddDomainAndProject(req);
        req.AddParameter("entityType", entityType, ParameterType.UrlSegment);
        client.ExecuteAsync<EntityResourceDescriptor>(req, (res) =>
            {
                if (res.ResponseStatus == ResponseStatus.Error)
                {
                    tcs.TrySetException(res.ErrorException);
                }
                else
                {
                    tcs.SetResult(res.Data);
                }
            }
        );
        return tcs.Task;
    }
Run Code Online (Sandbox Code Playgroud)

在这里我所能做的就是返回 Task 但调用者仍然无法获取响应数据,或者我是否遗漏了一些明显的东西?调用者可以订阅在 Task.Completed 等处触发的事件吗?

我对这个异步概念非常模糊。是否有编写可移植数据 API 的示例?

c# asynchronous restsharp

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

如何在C#中使用RestSharp反序列化动态json属性?

我有一个具有以下结构的Web服务(我无法编辑):

/用户

{
    "response" : {
        "users": [{"name": "John"},{"name": "Jack"}]
    },
    "page" : { "current":1, "total":1}
}
Run Code Online (Sandbox Code Playgroud)

/宠物

{
    "response" : {
        "pets": [{"name": "Fido"},{"name": "Tweety"}]
    },
    "page" : { "current":1, "total":1}
}
Run Code Online (Sandbox Code Playgroud)

如您所见,“响应”属性中的属性名称已更改。如何使用RestSharp反序列化一般响应?我不想为每个资源编写一个Response类。

我编写了以下通用Response类

{
    "response" : {
        "users": [{"name": "John"},{"name": "Jack"}]
    },
    "page" : { "current":1, "total":1}
}
Run Code Online (Sandbox Code Playgroud)

当然,RestSharp无法将动态json属性与ResponseBody.list属性链接。我怎样才能做到这一点?

c# json dynamic restsharp deserialization

2
推荐指数
1
解决办法
1716
查看次数

Restsharp XML 反序列化

我正在发布一个 get 请求,它返回一个 xml 文件,但是当我尝试将它反序列化为一个列表时,我收到以下错误:

{"没有为此对象定义无参数构造函数。"}

RestClient 类(调用 GetResourceList):

public T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient();
            client.BaseUrl = new Uri(m_URL);
            client.Authenticator = new HttpBasicAuthenticator(m_Username, m_Password);

            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var exception = new ApplicationException(message, response.ErrorException);
                throw exception;
            }
            return response.Data;
        }

        public List<resource> GetResourceList()
        {
            var request = new RestRequest();
            request.Resource = "resource";
            request.AddHeader("Accept", "application/xml"); …
Run Code Online (Sandbox Code Playgroud)

c# xml xsd restsharp deserialization

2
推荐指数
1
解决办法
2162
查看次数

RestSharp DownloadData与进度条同步

如何在窗体应用程序中通过ProgressBar下载文件并显示下载进度?

RestClient client = new RestClient("http://127.0.0.1/");

RestRequest request = new RestRequest("/test/{FileName}");
request.AddParameter("FileName", "testFile.abc", ParameterType.UrlSegment);

string path = @"C:/Users/[user]/Desktop/testFile.abc";

var fileForDownload = client.DownloadData(request);

fileForDownload.SaveAs(path);

if (File.Exists(@"C:/Users/[user]/Desktop/testFile.abc"))
{
    MessageBox.Show("done");
}
Run Code Online (Sandbox Code Playgroud)

我写这样的想法,但我现在不知道是什么?

c# restsharp

2
推荐指数
1
解决办法
2316
查看次数

如何删除 JSON 字符串中的开始和结束双引号以及所有反斜杠 - C#

为了使用 C# 执行 rest API 调用,我必须使用参数序列化字典。这些参数必须以 JSON 形式放置在请求正文中。

API 调用是在 RestSharp 的帮助下完成的。并使用 fiddler 检查发送字符串。

request.AddBody(_jsonrequeststring);
Run Code Online (Sandbox Code Playgroud)

问题是 API 非常挑剔,它不接受断点(反斜杠),也不接受 JSON 字符串开头和结尾的双引号。

所以这是它的期望:

{
    "ConsumerToken":"aconsumertoken",
    "UserId":"email@web.com",
    "PasswordSha256Base64":"apassword"
}
Run Code Online (Sandbox Code Playgroud)

这就是我要发送的内容:

"{ConsumerToken:\"aconsumertoken\",UserId:\"email@web.com\",PasswordSha256Base64:\"apassword\"}"
Run Code Online (Sandbox Code Playgroud)

我可以删除 \" 但是当它发送该字符串时它也会返回一个错误。

"{ConsumerToken:aconsumertoken,UserId:email@web.com,PasswordSha256Base64:apassword}"
Run Code Online (Sandbox Code Playgroud)

甚至可以删除 \ 和打开和关闭双引号吗?如果是这样怎么办?我似乎无法理解它。

完整的调用:

用户处理程序

public static object Login(string uname, string pass, string conTok)
{
    Dictionary<string, string> loginDictionary =
    new Dictionary<string, string>();
    loginDictionary.Add("ConsumerToken", conTok); 
    loginDictionary.Add("UserId", uname);
    loginDictionary.Add("PasswordSha256Base64", pass); 
    string jsonRequestString = JsonConvert.SerializeObject(loginDictionary);

    Proxy proxy = new Proxy(jsonRequestString); 
    return proxy.Execute();
}
Run Code Online (Sandbox Code Playgroud)

代理.cs

public class Proxy
{
    const string BaseUrl …
Run Code Online (Sandbox Code Playgroud)

.net c# json restsharp

2
推荐指数
1
解决办法
1954
查看次数

简单的RestSharp Post,让你失败

我有以下代码片段,一直对我失败:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

var client = new RestClient("https://api.mydomain.com:443");    
var request = new RestRequest("/Save?api_key=myKeyHere", Method.POST);
IRestResponse response = client.Execute(request);
var content = response.Content;

    if (response.ErrorException != null) {
        Response.Write(response.ErrorException);
    }
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外,上面的代码:

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote …
Run Code Online (Sandbox Code Playgroud)

restsharp

2
推荐指数
1
解决办法
1196
查看次数

RestSharp AddFile 将多部分表单标题添加到文件

我正在使用 RestSharp 的 AddFile 并且它几乎可以正常工作,除非我的文件由于添加了这个标题信息而最终被破坏。

-------------------------------28947758029299
Content-Disposition: form-data; name="user.png"; filename="user.png"
Content-Type: image/png
Run Code Online (Sandbox Code Playgroud)

这只是我上传的一张测试图片。如果我从文件中删除这些行,那么它可以正常打开,否则它似乎已损坏。我可以在不添加这些东西的情况下使用 AddFile 吗?

当前代码:

string contentType = MimeMapping.GetMimeMapping("~/uploads/" + filename); //image/png etc
request.AddFile(filename, Server.MapPath("~") + "\\uploads\\" + filename, contentType);
IRestResponse response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

还尝试了相同的结果:

request.AddHeader("Content-Type", contentType);
byte[] bytes = File.ReadAllBytes(Server.MapPath("~") + "\\uploads\\" + filename);
request.AddBody(new {myFile = File.ReadAllBytes(Server.MapPath("~") + "\\uploads\\" + filename) });
Run Code Online (Sandbox Code Playgroud)

还有这个(这里根本没有文件通过):编辑:这实际上有效

string contentType = MimeMapping.GetMimeMapping("~/uploads/" + filename);
byte[] bytes = File.ReadAllBytes(Server.MapPath("~") + "\\uploads\\" + filename);

request.AddHeader("Content-Type", contentType);
request.AddParameter(contentType, bytes, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

c# rest restsharp

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

Json Post 在 Postman 中有效,但在 C# 中无效

当我在 Postman 中尝试 Post 请求时,它给了我正确的响应,没有错误。当我使用 Postman 生成的 Restsharp 代码时,响应始终为空且没有错误。

var client = new RestClient("https://myurl/api/authenticate/authenticate");
        var request = new RestRequest(Method.POST);
        request.AddHeader("postman-token", "00497e4f-f58f-677d-f98a-bb972032c2eb");
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("content-type", "application/json");
        request.AddParameter("application/json", "{\n\t\"applicationKey\" : \"MYAPPLICATIONKEY\",\n\t\"userSecret\" : \"MYUSERSECRET\"\n}", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
Run Code Online (Sandbox Code Playgroud)

我试图用 postman-token、cache-control 删除行,但总是一样没有错误没有响应。(在响应中我应该得到访问令牌)

c# json restsharp

2
推荐指数
1
解决办法
6896
查看次数

在C#中使用属性反序列化XML

我无法从API调用反序列化XML响应.我的'Option'对象的属性'Description'为null.

以下是XML示例:

<vehicle found="1">
   <description>VehicleDescText</description>
   <buildDate>2000-11-20</buildDate>
   <modelYear>2001</modelYear>
   <optionList>
      <option code="UH8">OptionDesc1</option>
      <option code="UH8">OptionDesc2</option>
   </optionList>
</vehicle>
Run Code Online (Sandbox Code Playgroud)

以下是C#类的示例:

[DataContract]
[XmlRoot("vehicle")]
public class Vehicle
{
    [DataMember]
    [XmlAttribute("found")]
    public bool Found { get; set; }

    [DataMember]
    [XmlElement("description")]
    public string Description { get; set; }

    [DataMember]
    [XmlElement("buildDate")]
    public string BuildDate { get; set; }

    [DataMember]
    [XmlElement("modelYear")]
    public string ModelYear { get; set; }

    [DataMember]
    [XmlElement("optionList")]
    public List<Option> OptionList { get; set; }
}

public class Option
{
    [DataMember]
    [XmlAttribute("code")]
    public string Code { get; set; } …
Run Code Online (Sandbox Code Playgroud)

c# xml restsharp deserialization

2
推荐指数
1
解决办法
2779
查看次数

标签 统计

restsharp ×10

c# ×9

deserialization ×3

json ×3

xml ×2

.net ×1

asynchronous ×1

dynamic ×1

oauth-2.0 ×1

payload ×1

request ×1

rest ×1

xsd ×1