shahjagat
asked on
Jquery call to WCF Service Issues
Hello,
I am trying to call a WCF Service from Jquery.
When i run the application as of now, it goes into error.
All i get is : XHR: [object Object]
Earlier i was getting CORS issues.
I Included " "Access-Control-Allow-Orig in" under Application_Beginrequest of global.asax file.
Just to make sure the service is working good, I tried calling the service from a server side button control click and it works good and returns the data.
However, when i call it form Jquery, it goes into error and does nothing.
Can you point out what is wrong with this code? Why is it failing.
Service
Thanks in Advance
I am trying to call a WCF Service from Jquery.
When i run the application as of now, it goes into error.
All i get is : XHR: [object Object]
Earlier i was getting CORS issues.
I Included " "Access-Control-Allow-Orig
Just to make sure the service is working good, I tried calling the service from a server side button control click and it works good and returns the data.
However, when i call it form Jquery, it goes into error and does nothing.
Can you point out what is wrong with this code? Why is it failing.
Service
namespace EnrSvcOut
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IServiceEnrollmentOutcome
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetServicePrograms")]
List<SvcEnrOutProgram> GetServicePrograms();
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class SvcEnrOutProgram
{
int _SvcEnrOutProgramID ;
string _SvcEnrOutProgramName ;
[DataMember]
public int SvcEnrOutProgramID
{
get { return _SvcEnrOutProgramID; }
set { _SvcEnrOutProgramID = value; }
}
[DataMember]
public string SvcEnrOutProgramName
{
get { return _SvcEnrOutProgramName; }
set { _SvcEnrOutProgramName = value; }
}
}
}
namespace EnrSvcOut
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class MainService : IServiceEnrollmentOutcome
{
public List<SvcEnrOutProgram> GetServicePrograms()
{
List<SvcEnrOutProgram> capProgram = new List<SvcEnrOutProgram>();
clsSvcEnrOutCallsToDB CallDB = new clsSvcEnrOutCallsToDB();
capProgram = CallDB.GetServiceProgram();
return capProgram;
}
#region IServiceEnrollmentOutcome Members
//List<SvcEnrOutProgram> IServiceEnrollmentOutcome.GetServicePrograms()
//{
// throw new NotImplementedException();
//}
#endregion
}
}
Web.config:
<system.serviceModel>
<services>
<service name="EnrSvcOut.MainService" behaviorConfiguration="EnrSvcOut.MainServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding"
contract="EnrSvcOut.IServiceEnrollmentOutcome" behaviorConfiguration ="endPBehavior" >
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EnrSvcOut.MainServiceBehavior">
<!-- 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="endPBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Client Side JQuery Ajax call:
<script src="jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
function WCFJSON() {
var userid = "1";
Type = "GET";
Url = "http://localhost:60888/MainService.svc/GetServicePrograms";
ContentType = "application/json; charset=utf-8";
DataType = "jsonp"; varProcessData = true;
CallService();
}
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
data: null,
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
var items = [];
$(msg).each(function(index, Element) {
items.push($('<li/>').text(Element.ServiceProgramID));
});
$('#ul_ServiceProgram').append.apply($('#ul_ServiceProgram'), items);
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null;
varUrl = null;
Data = null;
ContentType = null;
DataType = null;
ProcessData = null;
}
function ServiceSucceeded(result) {
alert("In Success");
if (DataType == "json") {
resultObject = result.GetUserResult;
for (i = 0; i < resultObject.length; i++) {
alert("ResultObject : " + resultObject[i]);
}
}
}
function ServiceFailed(xhr) {
//alert("xhr : " + xhr.responseText);
alert("XHR: " + xhr);
//alert("xhr string : " + xhr.toString());
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
//error(err);
alert("Error as err :" + err);
else
//error({ Message: "Unknown server error."
alert("Unknown server error.");
}
return;
}
$(document).ready(
function() {
WCFJSON();
}
);
Thanks in Advance
Two quick things here:
1.)Which domain the error occurs?
2.)Which domain it works?
Based on the answers of the questions above you need to update your server side code,normally they wont allow localhost origin...but you can if you really need it by updating the regex expression they are using to filter domains(If they use any..).So first thing check your server side code and see where they are filtering domains for CORS.
1.)Which domain the error occurs?
2.)Which domain it works?
Based on the answers of the questions above you need to update your server side code,normally they wont allow localhost origin...but you can if you really need it by updating the regex expression they are using to filter domains(If they use any..).So first thing check your server side code and see where they are filtering domains for CORS.
ASKER
Ryan,
As i mentioned in the question, i have the code to allow CORS in Application_beginrequest under global.asax file.
Frank,
I tried to consume the service from server side to make sure there is no issue with the service.( This is just a test. This is not the way i want.)
I want to call the service from Jquery. I am testing on my development PC.
Thanks in Advance
As i mentioned in the question, i have the code to allow CORS in Application_beginrequest under global.asax file.
Frank,
I tried to consume the service from server side to make sure there is no issue with the service.( This is just a test. This is not the way i want.)
I want to call the service from Jquery. I am testing on my development PC.
Thanks in Advance
Hi Jagat,
Have you resolved this query? I am curious if you already have the answer, if not I would love to do a quick PoC to sort it out.
I have my doubts on couple of things i.e. using localhost:port and using FQDN of a computer will also be considered a violation when it comes to WCF/Jquery combo.
Regards,
Chinmay.
Have you resolved this query? I am curious if you already have the answer, if not I would love to do a quick PoC to sort it out.
I have my doubts on couple of things i.e. using localhost:port and using FQDN of a computer will also be considered a violation when it comes to WCF/Jquery combo.
Regards,
Chinmay.
ASKER
This issue is resolved. I do not remember what fixed the issue. But , as of now, it works.
As mentioned in the question, Allow CORS was already included in the global.asax when i was getting this error. I had to something else to fix this issue.
Please close this question.
Thanks
As mentioned in the question, Allow CORS was already included in the global.asax when i was getting this error. I had to something else to fix this issue.
Please close this question.
Thanks
You can describe the solution and award yourself the answer points. As an author, ideally you should close the question.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIALMembers can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
to resolve this, you need to add the http response header to allow CORS, whether it's via IIS configuration wizard or via C# scripts.
some readings:
Getting started with the IIS CORS Module
https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
Access-Control-Allow-Origi
https://hk.saowen.com/a/6cf5754fc66c3267c32759e352cebe9c588e512cefb0e02c3089d3176362d7f8