Consuming .Net WCF Rest in different ways

3 篇文章 0 订阅

.Net friendly

SATURDAY, SEPTEMBER 4, 2010

Consuming .Net WCF Rest in different ways

There are different ways to consume wcf rest services in .net, The basic idea is first creating the http request and include the message body and message header. we need to serialize the objects we are going to send, then we need to send the request and then get the response and deserialize to get the response objects. 

How to make the request body and how to serialize and deserialize depends on the service method body style that can be Bare or Wrapped, To get some idea about this subject, you can have a look at my post Wrapped BodyStyle in WCF Rest
Please be aware that I am not saying which one is the best way, I am exploring WCF Rest recently and I like to share what I learned with other people. I will be happy to see what other people think.

I am going to show an example:

using System.ServiceModel.Web;
using System.ServiceModel;
using System.Net;
using MyWcfServiceLibrary;
 
namespace MyWcfServiceLibrary
{
    //POCO Entity
    public class Tag
    {
        public int ID { get; set; }
        public string TagName { get; set; }
        public byte Status { get; set; }
    }
 
    [ServiceContract(Namespace = "http://mytagservice")]
    public interface ITagService
    {
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "tags/{id}", 
Bodystyle=WebMessageBodyStyle.Bare)]
        int UpdateTag(string id, Tag tag);
    }
 
    public class TagService : ITagService
    {
        public int UpdateTag(string id, Tag tag)
        {
            return 1;
        }
    }
 
 
    //Consuming WCF Rest using WebChanelFactory
    //-----------------------------------------------------------------------
 
    public class Consumer
    {
        private void ConsumeWcfRset1()
        {
            string url = "http://something/MyWebsite/tagservice";
 
            Tag tag1 = new Tag() { ID = 11, TagName = "test", Status = 1 };
            WebChannelFactory<ITagService> cf = new WebChannelFactory<ITagService>(new Uri(url));
            ITagService channel = cf.CreateChannel();
            using (new OperationContextScope(channel as IContextChannel))
            {
                int i = channel.UpdateTag("1", tag1);
            }
        }
 
        //Consuming WCF Rest using HttpWebRequest
        //----------------------------------------
 
        private void ConsumeWcfRest2()
        {
            string url = "http://something/MyWebsite/tagservice";
            Tag tag1 = new Tag() { ID = 11, TagName = "gfgf", Status = 1 };
            HttpWebRequest req = HttpWebRequest.Create(url + "/tags/1") as HttpWebRequest;
            req.Method = "PUT";
            string content = DoSerialize(tag1, "");
            System.Text.UTF8Encoding en = new System.Text.UTF8Encoding();
            byte[] bArray = en.GetBytes(content);
            req.ContentLength = bArray.Length;
            req.ContentType = "text/xml";
            System.IO.Stream requestStream = req.GetRequestStream();
            requestStream.Write(bArray, 0, bArray.Length);
            requestStream.Close();
            HttpWebResponse res = req.GetResponse() as HttpWebResponse;
            System.IO.Stream stream = res.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            string str = sr.ReadToEnd();
            sr.Close();
        }
 
        //Consuming WCF Rest using HttpClient(Microsoft.Http in Microsoft WCF Rest Starter Kit)
        //------------------------------------------------------
        private void ConsumeWcfRset3()
        {
            string url = "http://something/MyWebsite/tagservice";
            Tag tag1 = new Tag() { ID = 11, TagName = "gfgf", Status = 1 };
            Microsoft.Http.HttpClient client = new Microsoft.Http.HttpClient();
            string content = DoSerialize(tag1, "");
            Microsoft.Http.HttpContent httpCon = Microsoft.Http.HttpContent.Create(content);
            client.DefaultHeaders.ContentType = "text/xml";
            Microsoft.Http.HttpResponseMessage res = client.Send(Microsoft.Http.HttpMethod.PUT, 
url + "/tags/1", httpCon);
            string str = new System.Text.UTF8Encoding().GetString(res.Content.ReadAsByteArray());
            client.Dispose();
        }
 
 
        private string DoSerialize(object obj, string rootName)
        {
            System.Runtime.Serialization.DataContractSerializer se;
            if (string.IsNullOrEmpty(rootName))
                se = new System.Runtime.Serialization.
DataContractSerializer(obj.GetType());
            else
                se = new System.Runtime.Serialization.
DataContractSerializer(obj.GetType(), rootName, "");
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            se.WriteObject(ms, obj);
            ms.Position = 0;
            byte[] arr = new byte[ms.Length];
            ms.Read(arr, 0, Convert.ToInt32(ms.Length));
            return new System.Text.UTF8Encoding().GetString(arr);
        }
    }
}


Cheers!

 

Original Source Version:
http://dotnetfriendly.blogspot.jp/2010/09/how-to-consume-net-wcf-rest.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值