Search code examples
c#restrestsharphttp-status-code-400

Why do I keep getting "Missing/Malformed URL Parameters" when consuming my API in C# (RestSharp) with VS 2022?


I'm trying to do a POST request in C#, using RestSharp, in Visual Studio 2022.

I tested the API using Postman, which was successful. The API requires a 64-bit encoded Basic Auth (which I have), and a unique API key (which I also have). I then looked at the C# Restsharp code provided by Postman, and tried to copy paste it into my VS project, but most of the libraries were deprecated. I then ended up modifying the code so it didn't give me any errors, and the code itself runs, but getting a semantic error: the request returns "Missing or Malformed URL parameters". In the body parameter, I send one parameter in the form

var body = @"{""fieldNameHere"": intHere}"; 

My full code (redacted):

        var options = new RestClientOptions("URLHERE")
        {
            Timeout = -1
        };
        var client = new RestClient(options);
        var request = new RestRequest
        {
            Method = Method.Post
        };

        request.AddHeader("API_KEY", "keyHere");
        request.AddHeader("Authorization", "authHere");
        request.AddHeader("Content-Type", "application/json");
        var body = @"{""fieldNameHere"": intHere}";
        request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        RestResponse response = await client.ExecuteAsync(request);

So I tried using a JObject for the parameter, got the same error, this is my code:

        JObject jObjectBody = new JObject();
        jObjectBody.Add("FieldName", intHere);

        request.AddParameter("application/json", jObjectBody, ParameterType.RequestBody);

            var clientValue = await client.ExecuteAsync(request);

        

I also tried using HttpWebRequest, but got an auth error so not sure what was going on there, didn't get that anywhere else. Would prefer to use RestClient anyway. This is the other way I tried to do the body parameter:

string postData = "{\"FieldNameHere\":" + intHere + "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

I haven't found anything that works yet. If someone can guide me towards a solution I'd be mad grateful, thanks. It definitely seems to be the body giving me the issue.


Solution

  • Ah! For some reason, phrasing my body like this worked:

    var body = new { FieldNameHere = intHere }
    request.AddJsonBody(body);
    

    I have no idea why this worked, but it did!

    A list of things that DID NOT work:

    • JObject technique
    • switching header placement
    • encoding the auth myself
    • how the RR instantiation is set up
    • with and without explicitly saying application/json (also including the charset and excluding)
    • using HttpWebRequest instead of RestSharp