Matt Dawdy
Matt Dawdy

Reputation: 19717

Pass complex object via http

I’ve got 2 projects that run on different servers but both have a reference to a common dll that contains a complex type called LeadVM. LeadVM contains sub-objects, like Employer which contains properties. Ex:

LeadVM.FirstName
LeadVM.LastName
LeadVM.Employer.Name
LeadVM.Employer.Phone

So, project 1 can create a LeadVM type of object, and populate it. I need to then, via an HTTP call, POST in the data to a controller/action in the 2nd project. The 2nd project knows what a LeadVM object is.

How can I...serialize(?) LeadVM and pass it to the accepting Action in the 2nd project?

EDIT: Thanks to @Unicorno Marley, I ended up using the Newtonsoft JSON stuff.

Now I just create my object in project 1, then do the following code (I'm sure it's clunky but it works).

LeadVM NewCustomer = new LeadVM();
NewCustomer.set stuff here....

var js = Newtonsoft.Json.JsonSerializer.Create();
var tx = new StringWriter();
js.Serialize(tx, NewCustomer);
string leadJSON = tx.ToString();

And then I can use HttpWebRequest to send a web request to my project 2.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1234/Lead/Create");
request.Method = "POST";
StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(System.Web.HttpUtility.UrlEncode(leadJSON));
streamOut.Close();
HttpWebResponse resp = null;
resp = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
sResponse = responseReader.ReadToEnd();
resp.Close();

In project 2, I can catch the json sent like this and my NewCustomer object in project 2 is already populated, ready for use.

var buffer = new byte[Request.InputStream.Length]; 
Request.InputStream.Read(buffer, 0, buffer.Length);
string json = System.Text.Encoding.Default.GetString(buffer);
json = System.Web.HttpUtility.UrlDecode(json);
LeadVM NewCustomer = Newtonsoft.Json.JsonConvert.DeserializeObject<PhoenixLead.LeadVM>(json);

I'm sure I'm doing things very awkwardly. I'll clean it up, but wanted to post the answer that I was led to.

Upvotes: 0

Views: 1069

Answers (1)

Unicorno Marley
Unicorno Marley

Reputation: 1894

Json is probably the most common option, there is a good json library for c# that can be found here:

http://james.newtonking.com/json

Alternatively, since youre just doing an HTTP post and you only have one object, the fastest option would just be to write out the data line by line and have the recipient machine parse it. Since they both know what a LeadVM is, and both presumably have the same definition, it would be trivial to read a text string into the proper variables. This quickly becomes the slower option if you decide to add more object types to this process though.

Upvotes: 2

Related Questions