2

I'm currently testing out writing a RESTful API with ASP.NET Web API. I'm using RestSharp on a client to simulate different calls.

I want to submit an application ID query string, and the body should be a collection of type "Log". Every time, the application ID get's posted by the body received by the server is always NULL.

Code on the server:

 public class LogsController : ApiController
{
    public HttpStatusCode Post(Guid ID, [FromBody] List<Log> logs)
    {
        if (logs != null)
            return HttpStatusCode.OK;
        else
            return HttpStatusCode.PreconditionFailed;
    }
}

public class Log
{
    public Guid ErrorId { get; set; }
}

Code on the client:

    static void Main(string[] args)
    {
        var client = new RestClient("http://localhost:36146/api");

        var json = JsonConvert.SerializeObject(new List<Log>()
            {
                new Log { ErrorId = Guid.NewGuid()}
            });

        var request = new RestRequest("Logs", Method.POST);

        request.RequestFormat = DataFormat.Json;
        request.AddParameter("ID", Guid.NewGuid(), ParameterType.QueryString);
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/json; charset=utf-8");
        request.AddBody(json);

        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
        Console.Read();
    }

    public class Log
    {
        public Guid ErrorId { get; set; }
    }

I thought I got this working, however no matter what I do now the "logs" parameter on the server is always NULL.

1
  • Paul - its great toknow that you found the solution, here is a link : codeproject.com/Articles/826359/… which describe the usage of RestSharp - might be helpful. Commented Oct 7, 2014 at 13:52

1 Answer 1

2

I think I've found the issue.

RestSharp implicitly uses the JsonSerializer when populating the body of the request. As I was also called the Serializer I think it caused issues with the formatting.

I've removed that call to the serializer and now I'm receiving a 200 back from the server.

Happy days.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use this library to switch to using Json.NET - nuget.org/packages/RestSharp.Newtonsoft.Json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.