简体   繁体   中英

Rest API Calls with RestSharp calling ASP.NET Web API

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM