编辑:问题的解决方案可以在John Sheehan的第一条评论中找到!
我想在我的项目中使用Restsharp作为Rest-Client.由于REST服务器尚未运行,我想在没有服务器的情况下测试客户端.我主要关注的是返回XML-Response的反序列化.是否可以在没有正确的RestSharp.RestResponse的情况下使用RestSharp反序列化XML?
我试过这样的:
public void testDeserialization()
{
XmlDeserializer d = new XmlDeserializer();
RestSharp.RestResponse response = new RestSharp.RestResponse();
string XML = @"<Response><Item1>Some text</Item1><Item2>Another text</Item2><Item3>Even more text</Item3></Response>";
response.Content = XML;
d.RootElement = "Response";
Response r = d.Deserialize<Response>(response);
}
public class Response
{
public string Item1 { get; set; }
public string Item2 { get; set; }
public string Item3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
反序列化创建Response-Class的Object,其中每个字段都为null.有没有办法测试RestSharp是否(以及如何)反序列化任何给定的xml?
编辑:为了更好的可读性 - 这是我正在使用的XML:
<Response>
<Item1>Some text</Item1>
<Item2>Another text</Item2>
<Item3>Even more text</Item3>
</Response>
Run Code Online (Sandbox Code Playgroud) 在我的Mvc Api控制器中,如果用户无法进行身份验证,则抛出HttpException 401.但是,RestSharp客户端似乎将其转换为Http 500状态代码.
我希望能够从我的Mvc控制器中抛出HttpExceptions,并让RestSharp客户端在其StatusCode属性中保留原始错误.
此外,我注意到如果服务器未启动,当RestSharp客户端发出请求时,响应的状态代码为0,响应代码为Error.RestSharp是否应该不返回404 http错误代码?
我真正需要的是关于RestSharp如何与HttpCodes一起工作的一些文档.
更新了我的api控制器中的代码:
throw new HttpException((int)HttpStatusCode.Unauthorized, AuthenticationError);
Run Code Online (Sandbox Code Playgroud) 我有一个Windows Phone 8客户端发出以下帖子请求:
public async Task<string> DoPostRequestAsync(String URI, JSonWriter jsonObject, ObservableCollection<byte[]> attachments)
{
var client = new RestClient(DefaultUri);
var request = new RestRequest(URI, Method.POST);
request.AddParameter("application/json; charset=utf-8", jsonObject.ToString(), ParameterType.RequestBody);
// add files to upload
foreach (var a in attachments)
request.AddFile("picture", a, "file.jpg");
var content = await client.GetResponseAsync(request);
return content;
}
Run Code Online (Sandbox Code Playgroud)
从RestSharp文档中我读到,通过向请求添加文件,它会自动作为"multipart/form-data"请求.
Play 2.1中的上传操作控制器如下:
@BodyParser.Of(BodyParser.Json.class)
public static Result createMessage() {
JsonNode json = request().body().asJson();
ObjectNode result = Json.newObject();
String userId = json.findPath("userId").getTextValue();
String rayz = json.findPath("message").getTextValue();
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart picture …Run Code Online (Sandbox Code Playgroud) 我对localhost服务器的一个请求有问题.
要进行身份验证,我需要两个cookie,一个来自sendReqForToken()方法,另一个来自sendLoginReq(字符串登录,字符串传递).
作为响应,我从sendLoginReq获取cookie,但不从sendReqForToken()获取cookie.
我不知道为什么一个请求有一个cookie第二个没有.
有趣的是,我从sendReqForToken()方法获得了正确的令牌(响应内容是正确的),但在响应头中没有任何cookie.
这是sendReqForToken()方法体:
public void sendReqForToken()
{
string adres = Globals.TOKEN_URL;
RestRequest request = new RestRequest(adres, Method.GET);
var client = new RestClient();
client.CookieContainer = new CookieContainer();
client.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
var tokenValue = JsonConvert.DeserializeObject<Token.RootObject>(response.Content);
DataManager.Instance.authToken = tokenValue.authenticity_token;
if (response.Cookies.Count > 0)
{
var cookie = response.Cookies.FirstOrDefault();
DataManager.Instance.cookieJar.Add(new Uri(Globals.TOKEN_URL), new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
}
}
else
{
}
});
}
Run Code Online (Sandbox Code Playgroud)
response.Cookies.Count总是等于0. response.cookies属性总是等于null.
这是sendLoginReq方法体:
public void sendLoginReq(string login, string pass)
{
login = …Run Code Online (Sandbox Code Playgroud) 我正在研究这个需要序列化JSON对象以使用RestSharp发布参数的项目,下面是我的代码:
var request = new RestRequest();
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
request.AddBody(jsonObject);
return client.Execute<dynamic>(request);
Run Code Online (Sandbox Code Playgroud)
我意识到的是,不是将每个JSON名称值对添加为post参数,而是request.AddBody将整个JSON字符串添加为一个大的post参数.我的问题是,有没有办法让request.AddBody方法将每个JSON名称 - 值对添加为单独的帖子参数?我知道这request.AddParameter()可以完成工作但需要手动添加每个参数.
代替:
[0]:{
application/json="
{
"name":"john doe",
"age": "12",
"gender": "male"}
}
}
Run Code Online (Sandbox Code Playgroud)
期望的结果:
[0]:"name":"john doe"
[1]:"age":"12"
[2]:"gender":"male"
Run Code Online (Sandbox Code Playgroud) 我已经实现了自己的自定义IAuthenticator调用OAuth2BearerAuthenticator,该自定义基本上接收一个ClientId,ClientSecret在发出任何请求之前,它会检查它是否具有有效的Bearer令牌-如果没有,它将使用客户端凭据消失并在继续操作之前“刷新”该令牌。原始请求。
Authenticate此自定义身份验证器的方法包含以下内容:
public void Authenticate(IRestClient client, IRestRequest request)
{
if (!bearerTokenExpiration.HasValue || bearerTokenExpiration.Value < DateTime.Now)
{
RefreshBearerToken();
}
if (request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
{
return;
}
request.AddHeader("Authorization", string.Format("Bearer {0}", bearerToken));
}
Run Code Online (Sandbox Code Playgroud)
我已经验证了它生成的载体令牌有效-我可以使用DHC(Chrome REST扩展)中的相同载体令牌授权标头从尝试访问的API成功请求数据
我还证实了if (any authorization paramaters)声明没有早日返回。
但是,RestSharp的响应失败 "HTTP Basic: Access denied.\n"
我不知道它是否相关,但响应中还包含WWW-Authenticate带有值的标头Basic realm=\"Web Password\"
任何帮助深表感谢。谢谢。
我想在camelCase中发布JSON,并按照这里的说明操作:
https://github.com/restsharp/RestSharp/wiki/Deserialization#overriding-jsonserializationstrategy
public class CamelCaseSerializerStrategy : PocoJsonSerializerStrategy
{
protected override string MapClrMemberNameToJsonFieldName(string clrPropertyName)
{
return char.ToLower(clrPropertyName[0]) + clrPropertyName.Substring(1);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我用这段代码创建一个新的客户端:
var client = new RestClient(_baseUrl);
SimpleJson.CurrentJsonSerializerStrategy = new CamelCaseSerializerStrategy();
Run Code Online (Sandbox Code Playgroud)
但是,在发出请求时,串行器未激活.RestSharp文档遍布整个地方,并且大部分都是错误的.查看源代码(RestRequest.AddBody),看起来根本不使用SerializerStrategy.
我一直在寻找一种在客户端级别进行此更改的方法,或者在不需要修改每个请求的地方.
我见过这个博客 - 也许这是唯一的方法.如果您只能在请求级别更改序列化策略,这似乎是RestSharp的一大步.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using RestSharp;
namespace ConsoleProgram
{
public class TryingOutRest {
public resttest Execute<resttest>(RestRequest request) where resttest : new() {
var client = new RestClient();
client.BaseUrl = new Uri("http://www.ocrwebservice.com");
client.Authenticator = new HttpBasicAuthenticator("apid", "apikey");
// the key and and id are put in as a string, but i removed them for the purposes of this.
var re_quest = new RestRequest();
re_quest.Resource = "/restservices/processDocument";
var response = client.Execute<resttest>(request);
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用RestSharp编码示例以连接到MailGun.在下面的代码中,请参阅:
client.Authenticator = new HttpBasicAuthenticator("XXX","key-yyyyyyyyyyyyyyyyyyyyyyy");
Run Code Online (Sandbox Code Playgroud)
有什么问题HttpBasicAuthenticator?VisualStudio说:
严重级代码描述项目文件行错误CS0246找不到类型或命名空间名称'HttpBasicAuthenticator'(您是否缺少using指令或程序集引用?)xTest_MailGun
注意:Visual Studio2015社区; RestSharp 105.2.3
这是代码:
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator = new HttpBasicAuthenticator("XXX","key-yyyyyyyyyy");
RestRequest request = new RestRequest();
Run Code Online (Sandbox Code Playgroud) 我正在使用REST API服务,并且在JSON的属性名称的Service输出中包含空格和保留字.当我尝试将其映射到C#类时出现问题,但我无法分配与此类似的属性名称.
如果我可以解决这个问题或者是否有其他替代方法,请告诉我.
以下是从服务返回的JSON:
{
"value": [ {
"accountNo": "JKBXXXXXXXXXVNX1",
"mainSalesPerson": "XXXXX",
"accountName": "XXXXXX",
"ledgerBalance": "-2,298.70",
"T+3": "0.00",
"T+4": "0.00",
"T+5 and Above": "2,298.70",
"riskRatedPortfolioValue": "109,057.50",
"exposure": "106,758.80",
"costToFirm": "",
"incomeToFirm": "14.59",
"costToIncome(%)": "",
"exposure(%)": "2.11",
"O/S Balance": "-2,298.70"
}],
"success": true
}
Run Code Online (Sandbox Code Playgroud)
我使用了以下映射C#类:
public class CountObject
{
public string value { get; set; }
public string success { get; set; }
}
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; …Run Code Online (Sandbox Code Playgroud) restsharp ×10
c# ×5
json ×4
rest ×2
.net ×1
api ×1
asp.net-mvc ×1
camelcasing ×1
cookies ×1
http-error ×1
http-post ×1
json.net ×1
oauth-2.0 ×1
post ×1
simplejson ×1
xml ×1