2009 m. lapkričio 29 d., sekmadienis

Communication between WCF and JBoss server via REST

Communication between WCF and JBoss server via REST

Targets:

  • Build a client to communicate with JBoss(Java application server) RESTEasy REST service
  • Use ssl combined basic auth to ensure security
  • Use direct xml - object serialization
  • Explore WCF REST Starter Kit possibilities

Issues:
  • Http 1.1 different standards interpretation by .NET and java
  • Adding custom xml namespace prefixes to request message

PART 1 - Simple client

Two different ways for calling REST from .NET :
  • Using simple HttpWebRequest and HttpWebResponse objects. (old way, more technical details)
  • Using WCF REST Starter Kit.

Let’s focus on the second type. It saves some lines of code and hides unnecessary technical details.
We have a task to create a user on the remote system and receive the status.

So far we’ve successfully created the following DTO objects (by using xsd tool that comes with Visual Studio or by hand:
  • Simplified user with id and Name fields
  • Status with success/failure indicator + optional message (failure case)
///
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(IsNullable = false, ElementName = "account")]
public class Account
{

private long idField;
private string name;

///
[System.Xml.Serialization.XmlElementAttribute(ElementName="id")]
public long Id
{
   get
   {

      return this.idField;
   }
  set
  {
     this.idField = value;
   }

}
[System.Xml.Serialization.XmlElementAttribute(ElementName = "name")]
public string Name
{
   get
   {
     return this.name;
   }
   set
   {
     this.name = value;
   }
}
}

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(IsNullable = false, ElementName = "status")]
public class Status
{

private string msg;
private bool successField;

///
[System.Xml.Serialization.XmlElementAttribute(ElementName = "msg")]
public string Msg
{
   get
   {
     return this.msg;
   }
   set
   {
     this.msg = value;
   }
}
[System.Xml.Serialization.XmlElementAttribute(ElementName = "success")]
public bool Success
{
   get
   {
     return this.successField;
  }
   set
   {
     this.successField = value;
   }

}
}


Then our code looks like:



using (HttpClient client = new HttpClient()) // needs disposal
{
  client.DefaultHeaders.ContentType = "text/xml";
  Account newAccount = new Account()
  {
     Id = 0,
     Name = “FirstUser”
  };

  HttpContentExtensions.CreateXmlSerializable<Account >(newAccount);
  HttpResponseMessage resp = lient.Post("http://example/account", newAccount);

  resp.EnsureStatusIsSuccessful(); // fires exceptions
  
  Status status = resp.Content.ReadAsXmlSerializable<Status>();
}

HttpContentExtensions class provides helper methods for Http content creation.

Next part will provide security for our client


Komentarų nėra:

Rašyti komentarą