美好的一天偷看,
我一直坚持这个问题大约6个小时,我无法弄清楚它有什么问题。首先,我正在尝试向服务器端点发送请求,这需要某种形式的基本身份验证作为json 。但是当它命中方法“Execute”时它会抛出一个空引用异常。不是下面的代码:
SomeObjectClass someObject = new SomeObjectClass();
RestRequest request = new RestRequest();
request.Method = Method.POST;
request.JsonSerializer = new CustomJsonSerializer();
request.RequestFormat = DataFormat.Json;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
var client = new RestClient();
client.BaseUrl = "https://www.somewebsite.com/someapi/something";
client.Authenticator = new HttpBasicAuthenticator("username","password");
client.AddHandler("application/json", new CustomerSerializer);
request.AddBody(someObject);
var result = client.Execute<dynamic>(request);
return result;
我一直在 NullReferenceException :
at RestSharp.HttpBasicAuthenticator.<Authenticate>b__0(Parameter p)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at RestSharp.HttpBasicAuthenticator.Authenticate(IRestClient client, IRestRequest request)
at RestSharp.RestClient.AuthenticateIfNeeded(RestClient client, IRestRequest request)
at RestSharp.RestClient.Execute(IRestRequest request, String httpMethod, Func`3 getResponse)
at RestSharp.RestClient.Execute(IRestRequest request)
at RestSharp.RestClient.Execute[T](IRestRequest request)
我最初的猜测是我对 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(委托{return true;}); 缺乏理解导致了这个问题,但我无法确定它。 我已经在这个问题上花了相当多的时间并试图发布问题,如果有专家可以提供答案,我将非常感激。
答案 0 :(得分:2)
我的解决方案是添加一个参数名称(我只有一个参数)。
更改前的代码:
//...set up client and create new request...
request.AddParameter(new Parameter()
{
//Name was not included and therefore null
Type = ParameterType.RequestBody,
Value = JsonConvert.SerializeObject(new
{
name,
domains,
custom_fields = customFields
})
});
HttpBasicAuthenticator
的{{3}}是抛出异常的地方,因为null
的{{1}}值未被处理。
Name
我将代码更改为以下内容并且有效:
if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))