0

I have a WCF service, I use it through JS by using Jquery calls.

The code looks like this:

IService1.cs:

[ServiceContract]
public interface IService1
{
    [WebInvoke(Method = "POST",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    User GetUser(string userName, string password);
}

Service1.cs:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{   
    public User GetUser(string userName, string password)
    {
        //DO SOMETHING
    }
}

Hosting done by IIS:

<%@ ServiceHost Language="C#" Debug="true" Service="MyProjectName.Service1" CodeBehind="Service1.svc.cs" %>

Web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <identity impersonate="false" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
                               multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MyProjectName.Service1" 
               behaviorConfiguration="ServiceBehavior">
        <endpoint address="" 
                  behaviorConfiguration="EndpBehavior" 
                  binding="webHttpBinding" 
                  contract="MyProjectName.IService1" />
      </service>
    </services>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>

In my java script page I call to GetUser function like that :

function CallService() {
    jQuery.ajaxSetup({
        error: function (x, e) {
            if (x.status == 0) {
                alert('You are offline!!\n Please Check Your Network.');
            } else if (x.status == 404) {
                alert('Requested URL not found.');
            } else if (x.status == 500) {
                alert('Internal Server Error.');
            } else if (e == 'parsererror') {
                alert('Error.\nParsing JSON Request failed.');
            } else if (e == 'timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n' + x.responseText);
            }
        }
    });
    var request = { userName: "aaa", password: "123" };
    var jsondata = JSON.stringify(request);

    $.ajax({
        type: "POST", //GET or POST or PUT or DELETE verb
        url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
        data: jsondata, //Data sent to server
        contentType: "application/json; charset=utf-8", // content type sent to server
        dataType: "json", //Expected data format from server
        processdata: true, //True or False
        crossDomain: true, //True or False
        success: function (result) {
           alert('success');
        }
    });
}

And although I can raise the service in the browser, I keep getting the error:

You are offline!! Please Check Your Network.

I can not find anything to help me solve it, anyone have an idea?

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111
  • http://stackoverflow.com/questions/872206/http-status-code-0-what-does-this-mean-in-ms-xmlhttp refer this – Bharath Jul 02 '13 at 06:12

2 Answers2

2

I think your problem is that your WS doesn't allow crossDomain access.

You can try adding the next code to your Web.config:

<configuration>
    <system.webServer>      
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
    <!-- Rest of your code -->
</configuration>
maqjav
  • 2,310
  • 3
  • 23
  • 35
  • @HodayaShalom What version of IIS are you using? – maqjav Jul 02 '13 at 06:32
  • 1
    @HodayaShalom here you have a link where they explain it http://forums.asp.net/t/1328833.aspx/1 – maqjav Jul 02 '13 at 06:43
  • 1
    @HodayaShalom I added more headers to the configuration, try with all of those. It seems that in IIS 7.5 you also need `` that's why I was asking about your version ;) – maqjav Jul 02 '13 at 06:52
  • Now I have an error when I try to send to service: Origin http://localhost is not allowed by Access-Control-Allow-Origin. What you have added to config should not solve it? – Hodaya Shalom Jul 02 '13 at 08:25
  • 1
    @HodayaShalom yes, we added support in the server to allow this, but I think your problem now is in your client side. Let me check :) – maqjav Jul 02 '13 at 08:50
  • @HodayaShalom Try modifing your contentType in your call to `contentType: "application/json"` – maqjav Jul 02 '13 at 08:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32732/discussion-between-hodaya-shalom-and-maqjav) – Hodaya Shalom Jul 02 '13 at 09:17
  • Finally I solved the problem by suggestion that this site:http://blog.weareon.net/calling-wcf-rest-service-from-jquery-causes-405-method-not-allowed/ – Hodaya Shalom Jul 04 '13 at 11:48
  • 1
    @HodayaShalom Hey Hodaya, nice to hear!, I'm glad you could fix it! – maqjav Jul 05 '13 at 05:24
  • Thanks @maqjav , you helped me alot ,because othervise i was going to spent too much time upon this.and in short my problem was that: i had my wcf service up running and deployed to my sub domain , but i could only call methods over browser ,in js i did not manage it until your suggest .Thanks – katmanco Dec 07 '14 at 19:00
  • For Those , who have both app and service in subdomains in a hosting environment , make your servcice url like **http://www.testservice.com/get** not **http://testservice.com/get** without "www" you have error **No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin** – katmanco Dec 07 '14 at 19:08
1

Don't know if you tried but use jsonp for cross site scripting.
Here is an example i found on the web. XSS-WCF-From-JQuery

Using JSONP is one technique to get around the limitations imposed by the same origin policy. JSONP has its pros and cons. Spend some time to research other methods that might better benefit your project requirements.

Mr T.
  • 4,278
  • 9
  • 44
  • 61
  • If I change the DataType to dataType: "jsonp", I do not comes to success function and not to error function. – Hodaya Shalom Jul 02 '13 at 06:38
  • @HodayaShalom - Well, it's not that simple. Your server need to know how to handle jsonp requests and it needs to know how to build a proper response. Here (http://blog.jonathanroussel.com/2010/01/jsonp-your-aspnet-web-service-direction.html) is an example of a HttpModule that you can use to generate jsonp responses. (in this example he uses asmx WS but im sure you will change what is necessary). – Mr T. Jul 02 '13 at 06:47
  • Still did not understand why it can not work with JSON. As it is now. – Hodaya Shalom Jul 02 '13 at 08:12
  • @HodayaShalom - Please read about same origin policy and JSONP. Here (http://en.wikipedia.org/wiki/JSONP) is the wikipedia explanation about JSONP with relevant links to related topics. In general, a web page that originated from www.server1.com cannot call via script to www.server2.com. There are some exceptions to this rule (like the – Mr T. Jul 02 '13 at 08:23