WCF Restful Service with Jquery Step by Step procedure

1.Create a Wcf Service Application
          -VS2008 ->New Project->Web->WCF Service Application->ProjectName
2.By Default you will get Iservice, Service and Service.svc file
          -Iservice
                   -Its is an Interface add some methods
                   -EX
          [OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetData?value={value}", ResponseFormat = WebMessageFormat.Json)]
        string GetData(string value);
        [OperationContract]
  [WebGet(UriTemplate = "/Result", ResponseFormat = WebMessageFormat.Xml)]
string GetData1();
-Service
          -Implement Iservice
3.In Service.svc file need to refer Service(right click on .svc file view markup)
          EX
                   <%@ ServiceHost Language="C#" Debug="true" Service="wcfrf1.Service1" CodeBehind="Service1.svc.cs" %>
4.In Web.Config add Endpoints and Endpoints Behaviors
          -EX    
<system.serviceModel>
            <services>
                  <service behaviorConfiguration="wcfrf1.Service1Behavior" name="wcfrf1.Service1">
                        <endpoint address="Json" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="JsonBehavior" contract="wcfrf1.IService1" name="RESTEP">
                              <identity>
                                    <dns value="localhost"/>
                              </identity>
                        </endpoint>
                        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
                        <endpoint address="Soap" binding="basicHttpBinding" contract="wcfrf1.IService1" name="Basic"/>
                  </service>
            </services>
            <behaviors>
                  <endpointBehaviors>
                        <behavior name="JsonBehavior">
                              <webHttp/>
                        </behavior>
                        <behavior name="wcfrf1.Service1Behavior">
                              <webHttp/>
                        </behavior>
                  </endpointBehaviors>
                  <serviceBehaviors>
                        <behavior name="wcfrf1.Service1Behavior">
                              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                              <serviceMetadata httpGetEnabled="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>
            </behaviors>
      </system.serviceModel>
5.host this wcf service in IIS and check in browser id you are getting error related to MIME
          Add .svc to applicationHost.config
Refer:
check in Browser now you can access the method
EX:
Create Website for accessing WCF via jquery
1.Add New Web Site
Add the following
<head runat="server">
    <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function() {
               
                $('#btnClick').click(function() {
                    $.ajax({
                        url: 'http://itsd002/wcfrf1/Service1.svc/Json/Result',
                        type: "GET",
                        dataType: "xml",
                        data: null,
                        success: function(response) {
                        var xmlstr = response.xml ? response.xml : (new XMLSerializer()).serializeToString(response);
                        alert(xmlstr);
                        $('#result').html('' + xmlstr);
                        },
                                                error: function(e) {
                            $('#result').html("Unavailable!!!");
                        }
                    });
                    return false;
                });
            });
            function ServiceFailed(result) {
                alert('Service call failed: ' + result.status + '' + result.statusText);
              
            }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    SOAP:<asp:Label ID="lblSOAP" runat='server' ></asp:Label><br />
    REST:<asp:Label ID="lblREST" runat='server' ></asp:Label><br /><br />
    <%--<asp:TextBox ID="txtName" runat="server"></asp:TextBox>--%>
    <asp:Button ID="btnClick" runat="server" Text="Button" />
    </div>
    <div id="result">
   
    </div>
    </form>
</body>
Our WCFRest with Jquery is Ready to use
Note:
-Run in Chrome so that you can see Jquery Error (right Click inspect element)
-Add Global.asax file to service and add the following
protected void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.AppendHeader("Access-Control-Allow-Origin", "*");
           // Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET");
            Response.AppendHeader("Access-Control-Allow-Headers", "x-requested-with");
        }
         
-Most Important both WCF Service and Website Should be in IIS then only it will work in all browser
-if Iservice “ ResponseFormat = WebMessageFormat.Xml” the in jquery datatype must be dataType: "xml",and in success method need to convert this to string var xmlstr = response.xml ? response.xml : (new XMLSerializer()).serializeToString(response);
                        alert(xmlstr);
-if if Iservice “ ResponseFormat = WebMessageFormat.Json” ” the in jquery datatype must be dataType: "Json"

Comments

Popular posts from this blog

How to Checkout External Repositories in Azure DevOps Build Pipeline: A Step-by-Step Guide

Cache Purging in Azure Front Door with Azure PowerShell and CLI