IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Appeler un WebService par POST via console [Débutant]


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2013
    Messages
    46
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2013
    Messages : 46
    Par défaut Appeler un WebService par POST via console
    Bonjour bonjour,

    Je suis débutant en C# est je m'attaque a un projet plutôt complexe.

    Le but de mon projet est de lire un fichier XML, le parser, et envoyer les données sur un WebService pour que mes données soit traitées et stockées dans une BDD par celui-ci.

    J'ai donc deux projet un type console, est un ASP.NET contenant mon WEBService (ServiceStack).

    Mon problème se pose lorsque j'essaye de "poster" une donnée, j'ai matte plein de tutos mais je ne sais pas trop a quoi va ressembler ma réponse ou le succès de mon "postage". D’après ce que j'ai compris je devrais recevoir sur ma console une réponse si mon information a été posté.

    Deuxième problème, comment envoyer toute les infos de mon fichier xml en un coup, sachant que j'ai déjà de-sérialiser mon fichier? Je n'ai vraiment aucune idée de la marche a suivre.

    Je vous met mon code console pour le post:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /// ------------------- POST ----------------------
    ///
     
    //string url = "http://localhost:55867/xml/reply/Gateway_Registration_Payload";
    //string xml_data = LHRP.Device_Info.Type;
     
    HttpWebRequest httpWReq =
        (HttpWebRequest)WebRequest.Create("http://localhost:55867/xml/reply/Gateway_Registration_Payload");
     
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "username=user";
    postData += "&password=pass";
    byte[] data = encoding.GetBytes(postData);
     
    httpWReq.Method = "POST";
    httpWReq.ContentType = "application/x-www-form-urlencoded";
    httpWReq.ContentLength = data.Length;
     
    using (Stream stream = httpWReq.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
     
    HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
     
    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    Mon code web service ressemble a ca:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    /// <summary>
    ///     Define your ServiceStack web service request (i.e. Request DTO).
    /// </summary>
    /// <remarks>The route is defined here rather than in the AppHost.</remarks>
    [Api("GET or DELETE a single movie by Id. Use POST to create a new Gateway_Registration_Payload and PUT to update it")]
    [Route("/Gateway_Registration_Payload", "POST,PUT,PATCH,DELETE")]
    [Route("/Gateway_Registration_Payload/{Id}")]
    public class Gateway_Registration_Payload : IReturn<Gateway_Registration_Payload_Response>
    {
        /// <summary>
        ///     Initializes a new instance of the movie.
        /// </summary>
        public Gateway_Registration_Payload()
        {
            this.Genres = new List<string>();
        }
        /// <summary>
        ///     Gets or sets the id of the movie. The id will be automatically incremented when added.
        /// </summary>
        [AutoIncrement]
        public int Id { get; set; }
     
        public int SessionID { get; set; }
        public List<string> Genres { get; set; }
    }
     
    /// <summary>
    ///     Define your ServiceStack web service response (i.e. Response DTO).
    /// </summary>
    public class Gateway_Registration_Payload_Response
    {
        /// <summary>
        ///     Gets or sets the movie.
        /// </summary>
        public Gateway_Registration_Payload Gateway_Registration_Payload { get; set; }
    }
     
    /// <summary>
    ///     Create your ServiceStack restful web service implementation.
    /// </summary>
    public class Gateway_Registration_Payload_Service : Service
    {
        /// <summary>
        ///     GET /Gateway_Registration_Payload/{Id}
        /// </summary>
        public Gateway_Registration_Payload_Response Get(Gateway_Registration_Payload Gateway_Registration_Payload)
        {
            return new Gateway_Registration_Payload_Response
                       {
                           Gateway_Registration_Payload = Db.Id<Gateway_Registration_Payload>(Gateway_Registration_Payload.Id),
                       };
        }
     
        /// <summary>
        ///     POST /Gateway_Registration_Payload
        ///     returns HTTP Response =>
        ///     201 Created
        ///     Location: http://localhost/ServiceStack.MovieRest/Gateway_Registration_Payload/{newGateway_Registration_PayloadId}
        ///     {newMovie DTO in [xml|json|jsv|etc]}
        /// </summary>
        public object Post(Gateway_Registration_Payload Gateway_Registration_Payload)
        {
            Db.Insert(Gateway_Registration_Payload);
            var newGateway_Registration_PayloadId = Db.GetLastInsertId();
     
            var newGateway_Registration_Payload = new Gateway_Registration_Payload_Response
                               {
                                   Gateway_Registration_Payload = Db.Id<Gateway_Registration_Payload>(newGateway_Registration_PayloadId),
                               };
     
            return new HttpResult(newGateway_Registration_Payload)
                       {
                           StatusCode = HttpStatusCode.Created,
                           Headers =
                               {
                                   {HttpHeaders.Location, base.Request.AbsoluteUri.CombineWith(newGateway_Registration_PayloadId.ToString())}
                               }
                       };          
        }
     
        /// <summary>
        ///     PUT /Gateway_Registration_Payload/{id}
        /// </summary>
        public object Put(Gateway_Registration_Payload Gateway_Registration_Payload)
        {
            Db.Update(Gateway_Registration_Payload);
     
            return new HttpResult
                       {
                           StatusCode = HttpStatusCode.NoContent,
                           Headers =
                               {
                                   {HttpHeaders.Location, this.RequestContext.AbsoluteUri.CombineWith(Gateway_Registration_Payload.Id.ToString())}
                               }
                       };
        }
     
        /// <summary>
        ///     DELETE /Gateway_Registration_Payload/{Id}
        /// </summary>
        public object Delete(Gateway_Registration_Payload request)
        {
            Db.DeleteById<Gateway_Registration_Payload>(request.Id);
     
            return new HttpResult
                       {
                           StatusCode = HttpStatusCode.NoContent,
                           Headers =
                               {
                                   {HttpHeaders.Location, this.RequestContext.AbsoluteUri.CombineWith(request.Id.ToString())}
                               }
                       };
        }
    }
    Merci d'avance pour votre aide,
    N’hésitez pas a me re-poser des questions je ne pense pas avoir été très clair dans mon sujet.
    Benmaster1

  2. #2
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    Si c'est OK, le StatusCode de la requête devrait être 200 : http://msdn.microsoft.com/en-us/libr...tatuscode.aspx

  3. #3
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2013
    Messages
    46
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2013
    Messages : 46
    Par défaut Pas de reponse..
    Bonjour GuruuMeditation et merci de ta reponse,

    Je ne reçois rien, enfin pas de message sur ma console, je doit bien m'attendre a ça? Je suis vraiment débutant.

    Ce que je veux savoir c'est comment envoyer une donner par un post a mon webservice et savoir si il a bien été poste ou non. même sil me dit mer.. ça me va mais je n'ai rien.

    J'ai teste ce code aussi :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
                    //XDocument Sendingxml = xml;
     
                    string xml_data = LHRP.Device_Info.Type;
     
                    //  string Sendingxml = "<?xml version=1.0 encoding=UTF-8> <PluginData> <Credential UserName=avosfieldagent01 AuthenticationToken=61cc3957744742dca238c4dd7cbca702 /><Session><PropertyAddress>5 Crosskey</PropertyAddress><PropertyAddress2/><PropertyCity>California</PropertyCity><PropertyState>CA</PropertyState><PropertyZip>92620</PropertyZip><PropertyType>Condo</PropertyType><SourceReferenceId>45643</SourceReferenceId><SessionId>2013070100158346</SessionId><SessionCompleteReturnURL/><CustomerId/><BluebookOrderCheckSum>681a598cf23f412095f6092c281823e6</BluebookOrderCheckSum><BluebookOrderId>11160</BluebookOrderId> </Session></PluginData>";
     
                    // Create a request using a URL that can receive a post. 
                    System.Net.WebRequest request = System.Net.WebRequest.Create("http://localhost:55867/xml/reply/Gateway_Registration_Payload");
                    // Set the Method property of the request to POST.
                    request.Method = "POST";
     
     
                    byte[] byteArray = Encoding.UTF8.GetBytes(xml_data);
     
                    // Set the ContentType property of the WebRequest.
                    request.ContentType = "text/xml; encoding='utf-8'";
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = byteArray.Length;
                    // Get the request stream.
                    Stream dataStream = request.GetRequestStream();
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    // Close the Stream object.
                    dataStream.Close();
                    // Get the response.
                    WebResponse response = request.GetResponse();
                    // Display the status.
                    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                    // Get the stream containing content returned by the server.
                    dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    Console.WriteLine(responseFromServer);
                    // Clean up the streams.
                    reader.Close();
                    dataStream.Close();
                    response.Close();

    Et pas de réponse non plus, pas d’exception non plus, pour les deux codes de POST...
    Je doit avouer que je suis vraiment confus sur ce projet je ne sais pas comment m'organiser.

  4. #4
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2013
    Messages
    46
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2013
    Messages : 46
    Par défaut Enfin une réponse!
    Bon J'arrive enfin a quelque chose
    Je fait mon POST de cette maniere:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
     
    string xml_data = "YO";
     
                // Create a request using a URL that can receive a post. 
                System.Net.WebRequest request = System.Net.WebRequest.Create(URLtest);
                // Set the Method property of the request to POST.
                request.Method = "POST";
     
     
                byte[] byteArray = Encoding.UTF8.GetBytes(xml_data );
     
                // Set the ContentType property of the WebRequest.
                request.ContentType = "text/xml; encoding='utf-8'";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                Console.WriteLine(responseFromServer);
                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();
                Console.ReadLine();
    Ma console m'affiche ca:
    "
    OK
    <?xml version="1.0" encoding="UTF-8"?>
    <string xmlns="example.abc/">Yo world!</string>
    "

    Et le code de mon Webservice c'est ca:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
        public class ServiceConvertion : System.Web.Services.WebService
        {
            //string MyString = "error";
            [WebMethod(Description = "show simple message")]
            public string HelloWorld()
            {
                return "Yo world!";
            }
        }
    J'aimerai que mon webservie affiche mon message poste, pourvez vous me dire comment reccuperer mon string please???

  5. #5
    Membre Expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Par défaut
    Tu peux parser le XML. C'est la seule façon je pense.

  6. #6
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2013
    Messages
    46
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2013
    Messages : 46
    Par défaut Parser... dé-sérialiser?
    Merci GuruuMeditation,

    J'ai déjà deserialiser mon xml avec mon code console, mais deserialiser c'est bien la même chose que parser? non?
    Je doit parser de quel cote? webservice ou console?

    Et pour mon post, j'ai déjà essaye d'envoyer mes données par un post normal en mode page web, pour ca j'ai du attribuer une propriete name a ma balise, cela me permet de reconnaître ma donnée, mais comment attribue cette propriété par un post via ma console, c'est ça que je ne sais pas faire.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Appel de Webservice par URL: passage de tableau
    Par JScorcho dans le forum Services Web
    Réponses: 0
    Dernier message: 28/04/2011, 23h02
  2. [JAX-WS] appel d'un WS par POST et pas GET
    Par Le Marlou dans le forum Services Web
    Réponses: 2
    Dernier message: 31/01/2010, 20h55
  3. Appel du navigateur par défaut et méthode POST
    Par Pascal Fonteneau dans le forum Web & réseau
    Réponses: 2
    Dernier message: 23/01/2008, 07h56
  4. Appel d'un webservice par un client
    Par ilhamita dans le forum Services Web
    Réponses: 0
    Dernier message: 20/11/2007, 11h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo