WCF Part2
Ways to Consume WCF services :
I created a solution and consumed the Service in diferents ways for REST (json format)and for SOAP (XML format) so that you can have an idea how does it work from front-end side.
First, I created a solution with WCF proyect hosted on IIS (svc file) and another as a client to consume Service.
file svc is pointing to my Service class which can be located as a dll in bin file or AppCode folder as a class or another way.
<%@ ServiceHost Language="C#" Debug="true" Service="MyWcfService.MyService" CodeBehind="MyService.svc.cs" %>
to simplify this and focuses only how to call it, i will rule out Service contract and implementations from backend side.
Now , I leave you here the webconfig file so that you can see how many bindings i configured and dif. settings.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="dani">
<!-- 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="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="NoSecurity">
<security mode="None"/>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="dani" name="MyWcfService.MyService">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint address="bh" binding="basicHttpBinding" contract="MyWcfService.IMyService" />
<endpoint address="wh" binding="wsHttpBinding" contract="MyWcfService.IMyService" />
<endpoint address="rh" behaviorConfiguration="WebBehavior" binding="webHttpBinding"
contract="MyWcfService.IMyService"/>
<endpoint address="jh" binding="wsHttpBinding" bindingConfiguration="NoSecurity"
contract="MyWcfService.IMyService" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Now it is time to call Service :
I detail here diferent ways depending if you set WCF as rest or soap.
you can créate a simple asp.net client and place the following lines into it to call Service.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Webpage.aspx.cs" Inherits="WebApp.Webpage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
<script>
//For avoiding "No- Transport" error
//force cross-site scripting (as of jQuery 1.5)
jQuery.support.cors = true;
//Call Rest WCF Service
$(document).ready(function () {
$("#btnWCFREST").click(function () {
$.ajax({
type: "GET",
url: "https://localhost:1415/servicio/MyService.svc/rh/data?id=4",
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
//Call WCF Service exposed with BasicHttp binding
//SOAP request in order to call the Service method
var bhRequest = "<s:Envelope xmlns:s=\"https://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<GetData xmlns=\"https://tempuri.org/\">" +
"<value>8</value>" +
"</GetData>" +
"</s:Body>" +
"</s:Envelope>";
$(document).ready(function () {
$("#btnWCFBasicHttp").click(function () {
$.ajax({
type: "POST",
url: "https://localhost:1415/servicio/MyService.svc/bh/",
data: bhRequest,
timeout: 10000,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "https://tempuri.org/IMyService/GetData");
},
success: function (data) {
$(data).find("GetDataResponse").each(function () {
alert($(this).find("GetDataResult").text());
});
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
//Call WCF Service exposed with WSHttp binding
//SOAP request generated in order to call the Service method
var whRequest ="<s:Envelope xmlns:a=\"https://www.w3.org/2005/08/addressing\" xmlns:s=\"https://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">https://tempuri.org/IMyService/GetData</a:Action>" +
"<a:MessageID>urn:uuid:7fdde7b6-64c8-4402-9af1-cc848f15888f</a:MessageID>" +
"<a:ReplyTo>" +
"<a:Address>https://www.w3.org/2005/08/addressing/anonymous</a:Address>" +
"</a:ReplyTo>" +
"<a:To s:mustUnderstand=\"1\">https://localhost:1415/servicio/MyService.svc/jh</a:To>" +
"</s:Header>" +
"<s:Body>" +
"<GetData xmlns=\"https://tempuri.org/\">"+
"<value>9</value>"+
"</GetData>" +
"</s:Body>" +
"</s:Envelope>";
$(document).ready(function () {
$("#btnWCFWSHttp").click(function () {
$.ajax({
type: "POST",
url: "https://localhost:1415/servicio/MyService.svc/jh/",
data: whRequest,
timeout: 10000,
contentType: "application/soap+xml",
dataType: "xml",
async: false,
success: function (data, status, xhr) {
$(data).find("GetDataResponse").each(function () {
alert($(this).find("GetDataResult").text());
});
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
</script>
<div>
<input id="btnWCFREST" type="button" value="Call REST WCF using JQuery" />
<p>
<input id="btnWCFBasicHttp" type="button" value="Call BasicHttp binded WCF using JQuery" />
</p>
<p>
<input id="btnWCFWSHttp" type="button" value="Call WsHttp binded WCF using JQuery" />
</p>
</div>
</form>
</body>
</html>
you can call the Service from code source dinamically as stated in WCF Part 1.
you can make use one of the following clases to do that:
- HttpWebRequest for control
- WebClient for simplicity and brevity
- RestSharp for both on non-.NET 4.5 environments
- HttpClient for both + async features on .NET 4.5 environments
Do not forget that if you call from diferent domain from javascrip it will not allow you do it :
you may want to allow ajax CROSSDOMAIN :
you enable CORS.There's a good read with explanation and work around here: https://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx or you can take a look at this : https://stackoverflow.com/questions/17183569/wcf-service-call-from-ajaxcross-domain or this one : https://www.codeproject.com/Articles/223572/Calling-Cross-Domain-WCF-service-using-Jquery-Java
ALLOW IN WEBCONFIG FILE IN WCF HOSTED FILE:
Hope this can be of useful for you. Thanks :)
Comments
- Anonymous
August 06, 2016
so good about crossdomain :) - Anonymous
August 07, 2016
Exellent description folk! - Anonymous
September 02, 2016
Thanks very helpful. Will share website with my palsbuy nba 2k17 mt http://www.ezega.com/Communities/Blogs/ShowBlogDetails.aspx?Id=71494