WCF RESTful Service Description Model (XML)

by Mwwhited 7. June 2009 12:06

One of the problems with RESTful services is not having a description language to allow for easy enumeration of services. This extension method allows for service classes to be described in an XML format that is easy to understand.


        public static XElement GetWebGetServices(this object input)
        {
            return new XElement("services",
                from method in input.GetType().GetMethods()
                let webInvoke = method.GetCustomAttributes(typeof(WebInvokeAttribute), false).FirstOrDefault() as WebInvokeAttribute
                let webGet = method.GetCustomAttributes(typeof(WebGetAttribute), false).FirstOrDefault() as WebGetAttribute
                where ((Attribute)webInvoke ?? webGet) != null
                let webInvokeXml = webInvoke != null ? new XAttribute[]{
                        new XAttribute("uriTemplate", webInvoke.UriTemplate),
                        new XAttribute("bodyTyle", webInvoke.BodyStyle),
                        new XAttribute("requestFormat", webInvoke.RequestFormat),
                        new XAttribute("method", webInvoke.Method)                               
                    } : null
                let webGetXml = (webInvoke == null && webGet != null) ? new XAttribute[]{
                        new XAttribute("uriTemplate", webGet.UriTemplate),
                        new XAttribute("bodyTyle", webGet.BodyStyle),
                        new XAttribute("requestFormat", webGet.RequestFormat),
                        new XAttribute("method", "GET")
                    } : null
                let contentType = method.GetCustomAttributes(typeof(ContentTypeAttribute), false).OfType().FirstOrDefault()
                let description = method.GetCustomAttributes(typeof(DescriptionAttribute), false).OfType().FirstOrDefault()
                select new XElement("service",
                    new XAttribute("name", method.Name),
                    new XAttribute("returnType", method.ReturnType),
                    new XElement("invoke", webInvokeXml ?? webGetXml),
                    new XAttribute("contentType", contentType != null ? contentType.ContentType : ContentTypes.Text_XML),
                    new XAttribute("description", description != null ? description.Description : string.Empty),
                    new XElement("Parameters",
                        from parameter in method.GetParameters()
                        select new XElement("parameter",
                            new XAttribute("name", parameter.Name),
                            new XAttribute("type", parameter.ParameterType),
                            new XAttribute("position", parameter.Position)
                        )
                    )
                )
            );
        }

Tags: , ,

Programming

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

RecentPosts

Badges