0
votes

I've been fighting with trying to get data from a WCF service with no luck, I would appreciate your help, this is my code and I'm always getting "0 undefined" in the error function in the ajax call:

Service1.svc.cs

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public string GetData()
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string output = "It worked";

        return serializer.Serialize(output); 
    }
}

IService1.cs

    [OperationContract]
    [System.ServiceModel.Web.WebInvoke(Method = "POST",
        ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    string GetData();

Web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
          </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="MyService.Service1">
        <endpoint address="" binding="webHttpBinding" contract="MyService.IService1" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
          </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
        </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

jQuery call

<script type="text/javascript">

    $(document).ready(function () {
        CallMyService();
    });

    function CallMyService() {
        $.ajax({
            type: "POST",
            url: "http://localhost:54368/Service1.svc/GetData",
            data: '',
            dataType: "json",
            contentType: "application/json",
            success: ServiceSucceeded,
            error: ServiceFailed
        });
    }

    function ServiceFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }

    function ServiceSucceeded(result) {
        var resultObject = result.GetDataResult;
        alert(resultObject);
    }

</script>

If I try to consume the WCF service from a C# project by adding a service reference, I'm getting this:

Could not find default endpoint element that references contract 'myReference.IService1' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

Could it be related to the error? The WCF service is hosted in IIS locally.

I just don't know what else to check.

UPDATE:

I just found the solution, it turns out that I need to a Global.asax file in the WCF service solution with the following code:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

Where localhost is where your WCF service is located, after that, it works! Thanks a lot to the both of you that told me about the debugger for Javascript, that gave me the clue!!!

1
result.GetDataResult is giving you that error. You can debug your javascript from Google Chrome and see what values are coming back from result.Hakunamatata
I just changed it to:success: function (result){ alert(result.d); } with the same result. How do I debug javascript code from Google chrome?saman0suke
Instead of using alert(resultObject) in your jQuery script, use console.log(result). You can then view the result in your browser's dev console, that you usually open with the F12 key. Look for a tab called Console in the panel that opens.Schlaus
I'm getting: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.saman0suke
Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on Stack Overflow. See "Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?. BTW, it's "Thanks in advance", not "Thanks in advanced".John Saunders

1 Answers

0
votes

UPDATE:

I just found the solution, it turns out that I need to a Global.asax file in the WCF service solution with the following code:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

Where localhost is where your WCF service is located, after that, it works! Thanks a lot to the both of you that told me about the debugger for Javascript, that gave me the clue!!!