分享

httpwebrequest wcf rest service customer data class parameter

 复杂网络621 2017-01-06

Calling REST WebInvoke POST method with complex type arguments from ASP .NET client?

原文地址:https://social.msdn.microsoft.com/Forums/vstudio/en-US/f75e08f6-7661-4f08-9b95-13ca44472d5b/calling-rest-webinvoke-post-method-with-complex-type-arguments-from-asp-net-client?forum=wcf

Hello!

I am creating a WCF REST service
1) I have created a Person class with DataContract & DataMember.
2) I have created public class MyCollection<T> : List<T> using [CollectionDataContract()].
3) I have created a [ServiceContract()] named IPersonService.
4) I have created a public class PersonService : IPersonService having two methods implemented.
5) [ServiceContract()]
    public interface IPersonService
    {
        [OperationContract()]
        [WebInvoke(UriTemplate="/person/new", Method = "POST", RequestFormat=

WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
        void AddNewPerson(Person newperson);

        [OperationContract()]
        [WebGet(UriTemplate = "/all/", RequestFormat = WebMessageFormat.Xml, ResponseFormat =

WebMessageFormat.Xml)]
        MyCollection<Person> ListAllPersons();
    }
}

6) [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class PersonService : IPersonService
    {
 // My implementation code for ListAllPersons() and void AddNewPerson(Person newperson)
    }

7) Hosting environment => IIS 7.0
8) binding used => webHttpBinding
9) Tested method => ListAllPersons() (Result OK=> Results in XML output)

Problem:
1) My problem is how to consume WebInvoke + POST method named AddNewPerson(Person newperson) having complex type as an argument in ASP .NET client .aspx?
2) What will be the URI in that case? (MethodName + ?)
3) What will be the client code using WebHttpRequest/WebHttpResponse in ASP .NET without proxy & wsdl ?
4) Can AddNewPerson (POST method) be tested by Fiddler?

Thanks in advance.





1) see 2 and 3
2) The method URL is the base address + the URI template. In the case for the IIS-hosted example, the base address is the address of the .svc file (http://your-server-name/vdir/service.svc).
3) The code below shows it. Notice that you can use both JSON and XML as data formats, and the server will work for both
4) Yes, just replicate exactly what the HttpWebRequest would send, and it works just as well. The WCF service works regardless of which client is used to it, as long as it sends the appropriate request.

    public class Post_f75e08f6_7661_4f08_9b95_13ca44472d5b
    {
        [DataContract(Name = "Person", Namespace = "")]
        public class Person
        {
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public int Age { get; set; }
        }

        [CollectionDataContract(Name = "MyCollectionOf{0}")]
        public class MyCollection<T> : List<T>
        {
            public MyCollection() : base() { }
            public MyCollection(IEnumerable<T> collection) : base(collection) { }
        }
        
        [ServiceContract]
        public interface IPersonService
        {
            [OperationContract()]
            [WebInvoke(UriTemplate = "/person/new", Method = "POST",
                RequestFormat = WebMessageFormat.Xml,
                ResponseFormat = WebMessageFormat.Xml)]
            void AddNewPerson(Person newperson);

            [OperationContract]
            [WebGet(UriTemplate = "/all/",
                RequestFormat = WebMessageFormat.Xml,
                ResponseFormat = WebMessageFormat.Xml)]
            MyCollection<Person> ListAllPersons();
        }

        public class PersonService : IPersonService
        {
            static List<Person> allPeople = new List<Person>();

            public void AddNewPerson(Person newPerson)
            {
                allPeople.Add(newPerson);
            }

            public MyCollection<Person> ListAllPersons()
            {
                return new MyCollection<Person>(allPeople);
            }
        }

        static ServiceHost host;
        static string baseAddress = "http://" + Environment.MachineName + ":8000/Service";

        public static void Test()
        {
            // For this example only, self-hosting
            StartService();

            // on an IIS-hosted service, baseAddress is the address to the .svc file
            string addPersonOperationAddress = baseAddress + "/person/new";

            // We can send either JSON or XML request.
            Util.SendRequest(addPersonOperationAddress, "POST", "application/json", "{\"Name\":\"John Doe\",\"Age\":33}");
            Util.SendRequest(addPersonOperationAddress, "POST", "text/xml", "<Person><Age>32</Age><Name>Jane Roe</Name></Person>");

            // Now getting all people
            string getAllPersonsOperationAddress = baseAddress+ "/all/";
            Util.SendRequest(getAllPersonsOperationAddress, "GET", null, null);

            Console.WriteLine("Press ENTER to close service");
            Console.ReadLine();
            CloseService();
        }

        private static void CloseService()
        {
            host.Close();
        }

        private static void StartService()
        {
            host = new ServiceHost(typeof(PersonService), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(IPersonService), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
            host.Open();
        }
    }
    public static class Util
    {
        public static string SendRequest(string uri, string method, string contentType, string body)
        {
            return SendRequest(uri, method, contentType, body, null);
        }
        public static string SendRequest(string uri, string method, string contentType, string body, Dictionary<string, string> headers)
        {
            string responseBody = null;

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
            req.Method = method;
            if (headers != null)
            {
                foreach (string headerName in headers.Keys)
                {
                    switch (headerName)
                    {
                        case "If-Modified-Since":
                            req.IfModifiedSince = DateTime.Parse(headers[headerName]);
                            break;
                        default:
                            req.Headers[headerName] = headers[headerName];
                            break;
                    }
                }
            }
            if (!String.IsNullOrEmpty(contentType))
            {
                req.ContentType = contentType;
            }

            if (body != null)
            {
                byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
                req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
                req.GetRequestStream().Close();
            }

            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException e)
            {
                resp = (HttpWebResponse)e.Response;
            }

            if (resp == null)
            {
                responseBody = null;
                Console.WriteLine("Response is null");
            }
            else
            {
                Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
                foreach (string headerName in resp.Headers.AllKeys)
                {
                    Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
                }
                Console.WriteLine();
                Stream respStream = resp.GetResponseStream();
                if (respStream != null)
                {
                    responseBody = new StreamReader(respStream).ReadToEnd();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
                }
            }

            Console.WriteLine();
            Console.WriteLine("  *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*  ");
            Console.WriteLine();

            return responseBody;
        }
    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多