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?

1

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

11 Comments

@HodayaShalom What version of IIS are you using?
@HodayaShalom here you have a link where they explain it forums.asp.net/t/1328833.aspx/1
@HodayaShalom I added more headers to the configuration, try with all of those. It seems that in IIS 7.5 you also need <add name="Access-Control-Allow-Headers" value="*" /> that's why I was asking about your version ;)
@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 :)
@HodayaShalom Hey Hodaya, nice to hear!, I'm glad you could fix it!
|
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.

4 Comments

If I change the DataType to dataType: "jsonp", I do not comes to success function and not to error function.
@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 (blog.jonathanroussel.com/2010/01/…) 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).
Still did not understand why it can not work with JSON. As it is now.
@HodayaShalom - Please read about same origin policy and JSONP. Here (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 <script> tag). JSONP is a way to work around this rule.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.