Avatar billede lasserasch Juniormester
23. august 2012 - 08:39 Der er 1 kommentar

Poste til Rest Webservice fra C# med DTO objekt

Hejsa.

Jeg har et spørgsmål til hvordan man fra C# sender data til en REST Webservice.
Jeg kan sagtens kalde en REST webservice fra Jquery med et Json DTO objekt, og det virker alt sammen fint.

Men jeg har også brug for at gøre det fra min backend kode, hvilket driller mig lidt.

Jeg forsøger at få nedenstående kode til at virke.

Jeg har på min webserver sat Fiddler op, for at se det request som bliver sendt af sted fra min C# kode, og det ser ud til at være tomt.
Den kalder serveren, men den poster kun dette med : "{ }". Altså NADA....

I fiddler får jeg følgende vist for requestet :

-----------
POST http://sagsdata.local/Saveapplication HTTP/1.1
Content-Type: application/json
Host: sagsdata.local
Content-Length: 2
Expect: 100-continue

{}
-----------


Den burde have postet mit ApplicationDTO objekt med som en Json string.



Koden som jeg opretter mit Request med, ser således ud :


        public ResponseDTO SaveApplication(string userid, string privatekey, string applicationid, string address, string amount, string candidatename, string candidatetitle, string city, string contactemail,
            string contactname, string council, string department, string effectslongtermed, string effectsshorttermed, string enddate, string expenses, string focusarea,
            string institute, string institution, string phonenumber, string placename, string postalcode, string projectdescription, string projectpurpose, string projecttitle,
            string support, string targetarea, string targetgroup, string targetgroupsize, string type, string status)
        {
            // Check Security to make sure we are dealing with an authorized user.
            CheckSecurity(userid, privatekey);

            JavaScriptSerializer jss = new JavaScriptSerializer();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ApplicationDTO));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new UriBuilder(new Uri(ConfigurationManager.AppSettings["SagsdataWSUrl"] + "/Saveapplication")).Uri);

            // Configure WebRequest to Use POST and set ContentType to Json.
            request.Method = "POST";
            request.ContentType = "application/json";

            // Get the Application from SharePoint, to make sure that the application beeing updated belongs to the authorized user.
            ResponseDTO resp = GetApplication(applicationid, userid, privatekey);
            if (resp.HasError)
                return resp;

            Entities.ApplicationDTO applicationDTO = new ApplicationDTO();

            if (applicationDTO != null)
            {
                applicationDTO.Address = address;
                applicationDTO.Amount = amount;
                applicationDTO.Candidatename = candidatename;
                applicationDTO.Candidatetitle = candidatetitle;
                applicationDTO.City = city;
                applicationDTO.Contactemail = contactemail;
                applicationDTO.Contactname = contactname;
                applicationDTO.Council = council;
                applicationDTO.Department = department;
                applicationDTO.EffectsLongTermed = effectslongtermed;
                applicationDTO.EffectsShortTermed = effectsshorttermed;
                applicationDTO.EndDate = enddate;
                applicationDTO.Expenses = expenses;
                applicationDTO.Focusarea = focusarea;
                applicationDTO.Institute = institute;
                applicationDTO.Institution = institution;
                applicationDTO.Modified = DateTime.Now.ToString();
                applicationDTO.Phonenumber = phonenumber;
                applicationDTO.Placename = placename;
                applicationDTO.PostalCode = postalcode;
                applicationDTO.ProjectDescription = projectdescription;
                applicationDTO.Projectpurpose = projectpurpose;
                applicationDTO.ProjectTitle = projecttitle;
                applicationDTO.Status = status;
                applicationDTO.Support = support;
                applicationDTO.TargetArea = targetarea;
                applicationDTO.TargetGroup = targetgroup;
                applicationDTO.TargetGroupSize = targetgroupsize;
                applicationDTO.Type = type;
                applicationDTO.Tag1 = userid;
                applicationDTO.Tag2 = privatekey;
                applicationDTO.ID = applicationid;
            }


            // Create a byte array of the data we want to send 
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, applicationDTO);
                ms.Position = 0;
                byte[] data = new byte[ms.Length];
                ms.Read(data, 0, data.Length);

                // Set the content length in the request headers 
                request.ContentLength = data.Length;

                // Write data 
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(data, 0, data.Length);
                }
            }

            // Get response 
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream and set the ResponseMessage to the ResponseDTO entity.
                StreamReader reader = new StreamReader(response.GetResponseStream());
                resp.ResponseMessage = reader.ReadToEnd();
            }

            return resp;
        }



ApplicationDTO entiteten ser således ud :

    [Serializable]
    [DataContract]
    public class ApplicationDTO
    {
        public string ID { get; set; }
        public string Address { get; set; }
        public string Amount { get; set; }
        public string Candidatename { get; set; }
        public string Candidatetitle { get; set; }
        public string City { get; set; }
        public string Contactemail { get; set; }
        public string Contactname { get; set; }
        public string Council { get; set; }
        public string Department { get; set; }
        public string EffectsLongTermed { get; set; }
        public string EffectsShortTermed { get; set; }
        public string EndDate { get; set; }
        public string Expenses { get; set; }
        public string Focusarea { get; set; }
        public string Institute { get; set; }
        public string Institution { get; set; }
        public string Phonenumber { get; set; }
        public string Placename { get; set; }
        public string PostalCode { get; set; }
        public string ProjectDescription { get; set; }
        public string Projectpurpose { get; set; }
        public string ProjectTitle { get; set; }
        public string Support { get; set; }
        public string TargetArea { get; set; }
        public string TargetGroup { get; set; }
        public string TargetGroupSize { get; set; }
        public string Type { get; set; }
        public string Status { get; set; }
        public string Created { get; set; }
        public string Modified { get; set; }
        public string DeadlineRegional { get; set; }
        public string DeadlineNational { get; set; }
        public string Tag1 { get; set; }
        public string Tag2 { get; set; }

    }





Håber at en af jer gutter kan se hvad pokker jeg gør forkert :-)


Mvh.
Lasse
Avatar billede arne_v Ekspert
23. august 2012 - 19:30 #1
Maaske et dumt spoergsmaal (reletaivt ukendt omraade for mig), men skal der ikke [DataMember] paa de properties?
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
IT-kurser om Microsoft 365, sikkerhed, personlig vækst, udvikling, digital markedsføring, grafisk design, SAP og forretningsanalyse.

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester