Friday, 10 March 2017

Accessing WCF Web API

Create WCF with the following web invoke method:

1) In interface add web invoke
  [WebInvoke(Method = "GET", UriTemplate = "/Lead/{LeadId}",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle= WebMessageBodyStyle.Wrapped)]
        CompositeType GetLeadData(string LeadId);

2)Add in service
 [AspNetCompatibilityRequirements(RequirementsMode  = AspNetCompatibilityRequirementsMode.Allowed)]

Add following detail in web config for webHttpBinding
    <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information,
          set the values below to false before deployment -->
          <serviceMetadata  httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <!--<serviceDebug includeExceptionDetailInFaults="True"/>-->
        </behavior>
      </serviceBehaviors>
 <endpoint address="" binding="webHttpBinding"  contract=".IService1" behaviorConfiguration="EndpBehavior">

   <endpointBehaviors>
        <behavior name="basichttp">
          <clientVia />
        </behavior>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>

3) Access from console application
string url = "http://service/" + "488C7C54-0EFF-E611-80E4-005056A93809";
            WebRequest req = WebRequest.Create(@url);
            req.Method = "GET";
            req.ContentType = @"application/json; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
                Console.WriteLine(jsonResponse);
            }

No comments:

Post a Comment