wp-net / WordPressPCL

This is a portable library for consuimg the WordPress REST-API in (almost) any C# application
MIT License
335 stars 131 forks source link

Post.CreateAsync throws Error #364

Closed mshasib closed 3 months ago

mshasib commented 3 months ago

I am trying to create a Post and get the following error Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WordPressPCL.Models.Post' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.' Here is my code:

WordPressClient client = new WordPressClient("http://wpsite.com/wp-json/wp/v2/", defaultPath: "");

// Authentication
client.Auth.UseBasicAuth("user", "password");

// Create the post
Post post = new Post
{
   Title = new Title("Title"),
   Content = new Content()
   {
       Raw = "test"
   }
};
var response = await client.Posts.CreateAsync(post);
simonhammes commented 3 months ago

I can't reproduce this.

Your code snippet works fine for me, although I'm using the following constructor call: new WordPressClient("http://localhost:8080/wp-json/");

What version of .NET are you running?

mshasib commented 3 months ago

i'm using .NET 8.0

ThomasPe commented 3 months ago

Sounds like your server is returning an error instead of the expected result. Can you try to get that response?

mshasib commented 3 months ago

The response is returning a list of posts in an array and as the code is expecting just a post object, it's failing in the deserialization step. I'm running this on a wordpress site hosted on wordpress.org. Do you think that they changed the response on their api?

mshasib commented 3 months ago

I was able to find the source of the issue. I was passing in http instead of https in the URI