【问题标题】:RestSharp Basic Auth null reference exceptionRestSharp Basic Auth null 引用异常
【发布时间】:2014-04-19 06:22:38
【问题描述】:

祝你好运,

我在这个问题上停留了大约 6 个小时,我无法弄清楚它有什么问题。首先,我正在尝试向服务器端点发送一个请求,该端点需要某种形式的基本身份验证作为 json .但是当它遇到“执行”方法时,它会抛出一个空引用异常。不是下面的代码:

        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(delegate { return true; }); 缺乏了解导致了这个问题,但我无法确定它。 我已经在这个问题上花费了相当长的时间并求助于发布问题,如果有专家对此提供答案,将不胜感激。

【问题讨论】:

  • 哪行代码抛出异常?
  • @CharlieKilian client.Execute(request) 抛出该错误

标签: c# json json.net restsharp


【解决方案1】:

我的解决方案是添加一个参数名称(我只有一个参数)。

更改前我的代码:

//...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
  })
});

HttpBasicAuthenticatorLine 42 是引发异常的位置,因为未处理 Namenull 值。

if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))

我将我的代码更改为以下内容并且它有效:

request.AddParameter(new Parameter()
{
  Name = "",
  Type = ParameterType.RequestBody,
  Value = JsonConvert.SerializeObject(new
  {
    name,
    domains,
    custom_fields = customFields
  })
});

【讨论】:

    猜你喜欢
    • 2017-11-04
    • 2014-01-06
    • 1970-01-01
    • 2019-06-07
    • 2017-11-11
    • 2014-08-24
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多