I designed a WCF REST service and try to consume it via JQuery in html page. When I added the html page in the solution where WCF service was created, I was getting the result as per the need. But when I created the HTML Page in a different solution I started getting errors such as no element found and the returned result is null.
I put a debugger in the service and I noticed that even if the the Consumer html page is kept in a different solution it still hits the global.asax file when service is called, But its not hitting any of the Method. I even put "crossDomain:true," and "jQuery.support.cors = true;" in script for enabling Cross Domain problem as well as I have made changes in Global.asax file too but of no use. Please provide me the solution for the same asap.
I am placing the actual code with configuration files and DataContracts along with the HTML code here :
ICouponService.cs :
[ServiceContract]
public interface ICouponService
{
[OperationContract]
[WebInvoke(UriTemplate = "/GenerateCoupon",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
CouponData GenerateCoupon(CouponData objCustomerData);
[OperationContract]
[WebInvoke(UriTemplate = "/UpdateGeneratedCoupon",
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
ResponseMessage UpdateGeneratedCoupon(CouponData objCustomerData);
}
CouponService.cs :
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class CouponService : ICouponService
{
public CouponData GenerateCoupon(CouponData objCustomerData)
{
return objCouponData;
}
public ResponseMessage UpdateGeneratedCoupon(CouponData objCustomerData)
{
return objResponseMessage;
}
}
CouponData.cs :
[DataContract]
public class CouponData
{
[DataMember(EmitDefaultValue = false)]
public string Email { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Points { get; set; }
[DataMember(EmitDefaultValue = false)]
public string ActiveFlag { get; set; }
[DataMember(EmitDefaultValue = false)]
public string CouponCode { get; set; }
[DataMember(EmitDefaultValue = false)]
public string RequestID { get; set; }
[DataMember(EmitDefaultValue = false)]
public string LoyaltyID { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Result { get; set; }
[DataMember(EmitDefaultValue = false)]
public string ReturnFlag { get; set; }
[DataMember(EmitDefaultValue = false)]
public string UserName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Password { get; set; }
}
ResponseMessage.cs :
[DataContract]
public class ResponseMessage
{
[DataMember(EmitDefaultValue = false)]
public string Response { get; set; }
}
Global.asax : First I thought there might be some Header problem so I added the same in Global file as shown below :
protected void Session_Start(object sender, EventArgs e)
{
string sessionId = Session.SessionID;
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
EnableCrossDomainAjaxCall();
}
private void EnableCrossDomainAjaxCall()
{
if (!string.IsNullOrEmpty(Request.ServerVariables["HTTP_ORIGIN"]))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", Request.ServerVariables["HTTP_ORIGIN"]);
if (!string.IsNullOrEmpty(HttpContext.Current.Request.HttpMethod))
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" || HttpContext.Current.Request.HttpMethod == "POST" || HttpContext.Current.Request.HttpMethod == "GET")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
//HttpContext.Current.Response.End();
}
}
}
}
Web.config :
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="SAM_STORE_LoyaltyProgram_WCFLibrary.CouponService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
contract="SAM_STORE_LoyaltyProgram_WCFLibrary.ICouponService" />
</service>
<service name="SAM_STORE_LoyaltyProgram_WCFServices.qqq">
<endpoint address="" behaviorConfiguration="SAM_STORE_LoyaltyProgram_WCFServices.qqqAspNetAjaxBehavior"
binding="webHttpBinding" contract="SAM_STORE_LoyaltyProgram_WCFServices.qqq" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
<behavior name="SAM_STORE_LoyaltyProgram_WCFServices.qqqAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<dataContractSerializer maxItemsInObjectGraph="5000" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<bindings>
<webHttpBinding>
<binding maxBufferSize="5000" maxReceivedMessageSize="5000"
transferMode="Streamed">
<readerQuotas maxDepth="5000" maxStringContentLength="5000"
maxArrayLength="5000" maxBytesPerRead="5000" maxNameTableCharCount="5000" />
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Index.html (script used to call service):
<script src="js/jquery-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
var eMail;
var points;
var requestId;
var couponCode;
var returnFlag;
var userName;
var password;
//Generic function to call Service
function CallService() {
$.ajax({
type: Type,
url: Url,
data: Data,
contentType: ContentType,
dataType: DataType,
//crossDomain:true, --This is not working
processdata: ProcessData,
success: function (msg) {
ServiceSucceeded(msg);
},
error: function (msg) {
alert("Service Failed");
ServiceFailed(msg);
}
});
}
function SetGenerateCouponValues() {
eMail = $("#txtEmail").val();
points = $("#txtPoints").val();
requestId = $("#txtRequestId").val();
userName = 'username';
password = 'JEBtJHVu';
}
function DestroyGenerateCouponValues() {
eMail = null;
points = null;
requestId = null;
userName = null;
password = null;
}
function SetUpdateCouponValues() {
couponCode = $("#txtCode").val();
returnFlag = $("#txtFlag").val();
userName = 'username';
password = 'JEBtJHVu';
}
function DestroyUpdateCouponValues() {
couponCode = null;
returnFlag = null;
userName = null;
password = null;
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}
function GenerateCoupon() {
SetGenerateCouponValues();
Type = "POST";
Url = "ServiceURL";
Data = '{ "Email": "' + eMail + '", "Points": "' + points + '", "UserName": "' + userName + '", "Password": "' + password + '", "RequestID": "' + requestId + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json";
ProcessData = true;
method = "GenerateCoupon";
CallService();
DestroyGenerateCouponValues();
}
function UpdateGeneratedCoupon() {
SetUpdateCouponValues();
Type = "POST";
Url = "ServiceURL";
Data = '{ "CouponCode": "' + couponCode + '", "ReturnFlag": "' + returnFlag + '", "UserName": "' + userName + '", "Password": "' + password + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json";
ProcessData = true;
method = "UpdateGeneratedCoupon";
CallService();
DestroyUpdateCouponValues();
}
function ServiceSucceeded(result) {
if (DataType == "json") {
if (method == "GenerateCoupon") {
var string = "Coupon Code : " + result.CouponCode + "<br/>" + "Points : " + result.Points + "<br/>" + "Result : " + result.Result;
$("#resultCreate").html(string);
$("#lblCouponCode").text(result.CouponCode);
$("#lblPoints").text(result.Points);
$("#lblResult").text(result.Result);
}
else if (method == "UpdateGeneratedCoupon") {
var string = "Response : " + result.Response;
$("#resultDelete").html(string);
$("#lblResponse").text(result.Response);
}
}
}
/*function ServiceFailed(xhr) {
alert("FAIL" + xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}*/
$(document).ready(
function () {
//jQuery.support.cors = true; --This is not working
$("#btnsubmit").click(function () {
GenerateCoupon();
});
$("#btnUpdateGeneratedCoupon").click(function () {
UpdateGeneratedCoupon();
});
});
</script>
Please provide me the solution for the same asap.