Firstly you need create a class if you want to send
a complex object in WCF REST service request .Here is sample:
  public class Artist
    {
        public string SearchArtist { get; set; }
        public string State { get; set; }
        public string Suburb { get; set; }
        public string Postcode { get; set; }
        public DateTime DateForm { get; set; }
        public DateTime? DateTo { get; set; }
        public int TotalEventsToReturn { get; set; }
    }
Now import the following  namespace in your project
using System.Web.Script.Serialization;
and just copy and paste below code in
your project 
private void getArtist()
        {
           //Create object of Artist class
            Artist artist = new Artist();
            artist.DateForm
= DateTime.UtcNow;
           
artist.Postcode = "2000";
           
artist.SearchArtist = "artistname";
           
artist.State = "NSW";
           
artist.Suburb = "Sydney";
           
artist.TotalEventsToReturn = 80;
//If you want to add root
name as well in your Json request then you need to                          write below code as
well otherwise you can skip this code
            dynamic collectionWrapper = new
            {
               
artist = artist
            };
          //Create JavaScriptSerializer  object to serialize artist object to Json string
            JavaScriptSerializer js = new JavaScriptSerializer();
          // Json string after serialization
            string json = js.Serialize(collectionWrapper);
   // Make a http
web request with URL
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://local.liveguide.com.au/LiveGuideDataAPI.svc/GetArtistEvents");
// Set content type such as Json,Xml for response
            httpWebRequest.ContentType = "application/json;
charset=utf-8";
           
httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
               
streamWriter.Write(json);
               
streamWriter.Flush();
            }
 //Set header such as AccessToken or API Key, these are the
confidential     information so need to
send in Header. If you don’t need to send any such information than simply
remove this code
            httpWebRequest.Headers.Add("AccessToken", "5347-c48b-4803-9056-6869");
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
              //
Result as response for WCF Service
                var result = streamReader.ReadToEnd();
            }
        }
Noteè If you are getting compile time error ‘One or more types required to compile a dynamic expression
cannot be found. Are you missing a reference?’ then you just
need reference of  Microsoft.CSharp from assembly
 
No comments:
Post a Comment