wp-net / WordPressPCL

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

Create New media #193

Closed RBSystemService closed 3 years ago

RBSystemService commented 4 years ago

good evening,

I am writing to ask about a problem. I am trying to create a new image on my wordpress site.

I state that:

https://github.com/wp-net/WordPressPCL/wiki/Working-with-Media

when I try to run the create command I get this error:

Message:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WordPressPCL.Models.BadRequest' 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 (eg {"name": "value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List 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.

StackTrace:

   in Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (JsonReader reader, Type objectType, JsonContract contract)    in Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)    in Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)    in Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (JsonReader reader, Type objectType, Boolean checkAdditionalContent)    in Newtonsoft.Json.JsonSerializer.DeserializeInternal (JsonReader reader, Type objectType)    in Newtonsoft.Json.JsonConvert.DeserializeObject (String value, Type type, JsonSerializerSettings settings)    in Newtonsoft.Json.JsonConvert.DeserializeObject [T] (String value, JsonSerializerSettings settings)    in WordPressPCL.Utility.HttpHelper.CreateUnexpectedResponseException (HttpResponseMessage response, String responseString)    in WordPressPCL.Utility.HttpHelper. d20`1.MoveNext ()    in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task task)    in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task task)    in WordPressPCL.Client.Media. d5.MoveNext ()    in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task task)    in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task task)    in System.Runtime.CompilerServices.TaskAwaiter`1.GetResult ()    in SmartSyncSN.mod_WordPress.VB $ StateMachine_3_Creazione_Foto_WP.MoveNext () in C: \ Sorg_VBNET_2017 \ SmartSyncSN \ mod_WordPress.vb: line 146

maybe I have to set the "client.JsonSerializerSettings" property differently?

Thanks in advance

Luca

Edit 1: If i do step-by-step, including all source code in my solution, in the procedure

            response = await _httpClient.PostAsync($"{_WordpressURI}{route}", postBody).ConfigureAwait(false);

the variable response return this message...

"StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, [...]"

but the destination folder on FTP have all permission's right.

What i can do?

Edit 2: good evening,

i've tried to follow this issue:

https://github.com/wp-net/WordPressPCL/issues/156

isn't my case but i've done a 3 tests follow this topic: 1) remove definition of content-type from your source code; (same problem) 2) managed in .htaccess the content-type; (same problem) 3) take a look in cpanel of my site, nothing th content-type is already managed.

I don'd know what i can do...

i write here my code:

        var client = new WordPressClient("http://happyshoponline.it/wp-json/");

        string myFileName = @"C:\Sorg_VBNET_2017\SmartSyncSN\bin\Debug\Foto\0066131.jpg";
        //string myFileName = @"C:\Sorg_VBNET_2017\SmartSyncSN\bin\Debug\Foto\test_funny.jpg";
        //string myFileName2 = @"/appfoto/wallofdenial.jpg";

        client.AuthMethod = AuthMethod.JWT;
        await client.RequestJWToken("MyUser", "MyPass");

        // returns created media
        // for create media item you must read them to Stream. Media items can be audio, video, image, pdf ot any othe type supported by wordpress
        Stream s = File.OpenRead(myFileName);
        if (await client.IsValidJWToken())
        {
            var createdMedia = await client.Media.Create(s, "media.jpg");
            //var createdMedia2 = await client.Media.Create(myFileName2, "wallofdenial2.jpg");
            //var createdMedia3 = await client.Media.Create(myFileName, "wallofdenial2.jpg");
            //var result = await client.Media.Delete(166902);
        }

thanks for the help

Edit 3:

I've tried to force generic mime-type in a step-by-step test and WORKS!!!

Now the question is... Could modify your source for manual set mime-type?

ThomasPe commented 4 years ago

Hey, sorry for the late reply. I think we could add an optional override for mime type in the Media Create methods. If you want you can create a PR, otherwise I'll see when I have time to add this.

RBSystemService commented 4 years ago

Thanks for your reply, i think is a good think i could set a specific mime type. At the moment i solved the problem forcing a generic case without any mime type

If you modify source let me know.

Thanks a lot

Good Work

Have a nice day

ThomasPe commented 4 years ago

I updated the package to 1.7.0 with an optional override for the mimetype when uploading media. Please let me know if this works for you.

RBSystemService commented 4 years ago

Hi Thomas,

Thanks for your reply. I've tried to update it, but i cannot use it as well

I'm curious to know why i can't use the autodeterminate mime type, which could be the problem?

Thanks for the help

Have a nice day Luca

ThomasPe commented 4 years ago

Can you share what your working code looks like? Since changing the mimetype did work for you it has to be some server config issue, but I'm not quite sure where to look as I don't know your server setup either.

The serialization error you're seeing already means the request has failed though, it just wasn't able to parse it since it's expecting an Object and is getting an Array.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WordPressPCL.Models.BadRequest' because the type requires a JSON object (e.g. {"name": "value"}) to deserialize correctly.

Perhaps you could post the response the server send you.

RBSystemService commented 4 years ago

Yes, the function is a simple call to your function, the code is:

Public Async Function Creazione_Foto_WP(myFull_FileName_Locale As String, NomeFileRemoto As String) As Task(Of ProductImage)

    Dim ImmagAppenaUpl As MediaItem = New MediaItem

    Try

        pi_WP_ImmagAppenaUploadata = New ProductImage

        Try

            client.AuthMethod = AuthMethod.JWT
            Await client.RequestJWToken(U_FTP, P_FTP)

            If Await client.IsValidJWToken() Then

                Dim myStreams As Stream = File.OpenRead(myFull_FileName_Locale)

                'ImmagAppenaUpl = Await client.Media.Create(myStreams, NomeFileRemoto, "*")
                ImmagAppenaUpl = Await client.Media.Create(myStreams, NomeFileRemoto, "text/plain")

            End If

        Catch wpex As WPException
            Dim a = 0
        End Try

        Return pi_WP_ImmagAppenaUploadata

    Catch ex As Exception
        Dim a = 0
        Return pi_WP_ImmagAppenaUploadata
    End Try

End Function

the code line with * is the way i fund with the old version of your library

i don't know why if i send to create function the real extension (.jpeg) the mime-type who return the code is teocally right but return the error in JSON parsing