Restsharp: NullReferenceException for body parameters that don't have a name

Created on 5 Apr 2019  ·  20Comments  ·  Source: restsharp/RestSharp

Expected Behavior

I would not have to add a name, or the error message would be clearer that a parameter name was missing.

Actual Behavior

A NullReferenceException is thrown.

Steps to Reproduce the Problem

  1. Add a request body parameter without a name

This must be the issue in RestClient.ConfigureHttp (it's assuming the name is there):

var parameterExists =
                    request.Parameters.Any(p =>
                        p.Name.Equals(defaultParameter.Name, StringComparison.InvariantCultureIgnoreCase)
                        && p.Type == defaultParameter.Type);

Specifications

  • Version: 106.6.9.0
  • Platform: .NET Framework
  • Subsystem:

StackTrace


System.NullReferenceException: Object reference not set to an instance of an object.
at RestSharp.RestClient.<>c__DisplayClass172_0.b__8(Parameter p)
at System.Linq.Enumerable.AnyTSource
at RestSharp.RestClient.ConfigureHttp(IRestRequest request)
at RestSharp.RestClient.ExecuteAsync(IRestRequest request, Action2 callback, String httpMethod, Func4 getWebRequest)
at RestSharp.RestClient.ExecuteAsync(IRestRequest request, Action`2 callback, Method httpMethod)

All 20 comments

@vbenedichuk any reason why you don't want to submit a PR?

Closed in the next release. Breaking change!

Seems like we are missing some tests. Indeed body parameters don't need a name. I think a better fix would only check if the name is not empty for parameters that aren't of type body.

I updated the pull request to reflect your idea.

I only caught this issue because I was trying to understand RestSharp better. It doesn't seem to be an issue in the nuget package at this time.

Yeah, the new version isn't published yet. I made some more changes in preparation to move to better async handling and also to address some of the issues with exceptions handling

when it will be fixed?

I can see tha there is version 106.7.0 but my visual studio shows only 106.6.10 why?

Fixed in 106.9

This remains a problem in the latest build Alexey

@ronaldfeb I merged the PR that claimed to fix this issue, could you please post your code?

@alexeyzimarev i just have a simple post function that takes in a JSON object as the body. The name parameter for the body is null.

        public async Task<Result> postAsync(object objectToUpdate, string apiEndPoint)
        {
            Result result = new Result();

            try
            {
                var client = new RestClient(apiEndPoint);

                var request = new RestRequest(apiEndPoint, Method.POST);
                request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
                request.RequestFormat = DataFormat.Json;
                request.AddJsonBody(objectToUpdate);
                var response = await client.ExecuteTaskAsync(request);
                //var response = client.ExecuteDynamic(request);


                if (response.StatusCode != HttpStatusCode.Created)
                {

                    Console.WriteLine("Access Token cannot obtain, process terminate");
                    result.Success = false;
                    result.Message = response.ErrorMessage;
                    return result;

                }

                result.Success = true;
                result.Message = "OK";
                return result;

            }
            catch
            {
                throw;
            }

            // await Audit(_settings, new AuditEntry() { Action = EnumTypes.Actions.Add.ToString(), Area = "Testcase", AuditId = obj.key, DatetimeStamp = DateTime.Now, ClientId = userId, NewValue = obj, OldValue = null });
        }

The json body:

{
  "smartloadId": "string",
  "clientReference": "string",
  "smsRecipientMsisdn": "string",
  "deviceId": "string",
  "productId": 0,
  "amount": 0,
  "pinless": true,
  "sendSms": true,
  "orderRefID": 0
}

Could you paste the exception details, including the stack trace?

@alexeyzimarev (Fixed in 106.9)
My RestSharp Version (106.10.1)

MemberSignUp signup = new MemberSignUp()
{
Email = "TEST",
NickName = "TEST",
};
RestRequest req = new RestRequest("/my/resource", Method.POST);

        req.AlwaysMultipartFormData = true;
        req.AddHeader("content-Type", "multipart/form-data");
        req.AddJsonBody(signup);

but -> req.Parameters[1].Name = is empty.

how to set parameter name when i req.AddJsonBody()

image

I have a similar error
Code

string url = "http://????????????????????????????/reports/new/Report2_11_1?page=reports/new/Report2_11_1&rep_nd=04.03.2020&rep_nd_h=18&rep_nd_min=00&rep_kd=05.03.2020&rep_kd_h=18&rep_kd_min=00&&rep_nd_fact_time=&rep_nd_h_fact_time=00&rep_nd_min_fact_time=00&rep_kd_fact_time=&rep_kd_h_fact_time=00&rep_kd_min_fact_time=00&train_registration=1&kind_rep_type=1,2&four_report_save=4,5&usw=1007&ush=1108";
CookieContainer container = new CookieContainer();
RestClient client = new RestClient();
client.CookieContainer = container;

RestRequest request = new RestRequest(url, Method.GET);

Error

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'name')
   at RestSharp.RestRequest..ctor(String resource, Method method, DataFormat dataFormat)
   at RestSharp.RestRequest..ctor(String resource, Method method)

I tried on different versions: 106.10.1, 106.10.0б, 106.9.0
With a seem to be url work good

"http://????????????????????????????/reports/new/Report2_1_1?page=reports/new/Report2_1_1&rep_nd=01.01.2019&rep_nd_h=0
0&rep_nd_min=00&rep_kd=05.03.2019&rep_kd_h=23&rep_kd_min=59&rep_status=0,1,2,4,5,6,7,10&state_among_road=close&rep_stat
us_among_road=0,1,2,4,6,7,10&rep_flg_add_inv=0&rep_flg_add_inv_among=0&rep_conseq=null&rep_character=null&kind_rep_type
=3&rep_service=null&rep_subdivision=null&rep_nod0=null&rep_place0=null&rep_place0_id=null&rep_stan0_1_id=null&rep_stan0
_2_id=null&rep_place0_value=null&rep_object=null&nod_place=null&rep_asu=0,1,2,5,7,11,12,14,15,20,21&rep_asu_dop=1:1&flg
_alien_service=2&usw=1578&ush=705"

@veliev it is a different issue, please open a separate one

Ok, the issue of the request body parameter requiring to have a name is _fixed_. If there any other problems with the parameter name being null, please open a separate issue.

How did you add a breaking change (remove the parameterless constructor of Parameter class) without changing the major version?
I've tried to update from 106.2.1 to the latest version, assuming that if it has the same major (106) without breaking changes but NOT!

@bsalmeida like that. Ideally, the parameter class should be internal. We cannot accept parameters that aren't configured correctly since it creates more issues that people post here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stricq picture stricq  ·  6Comments

thomasd3 picture thomasd3  ·  5Comments

maximuss picture maximuss  ·  3Comments

weswitt picture weswitt  ·  3Comments

instriker picture instriker  ·  7Comments