# .NET and More > WPF, WCF, WF >  [RESOLVED] WCF service in local IIS and run with Jquery.

## sapator

Hi.
Is that so hard? Do i need cross domain stuff???
I am creating a simple WCF and i want to call it from local IIS. I cannot do it, whatever i try.
The service will work if i have it inside a web site but not stand alone.
Here is the data:


```
''Service:
Imports System.ServiceModel.Activation
Imports System.Web.Script.Serialization

' NOTE: You can use the "Rename" command on the context menu to change the class name "VSAPIAJAX" in code, svc and config file together.
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class VSAPIAJAX
    Implements IVSAPIAJAX

    Public Sub DoWork() Implements IVSAPIAJAX.DoWork
    End Sub

    Function test() As String Implements IVSAPIAJAX.test
        Return "g"
    End Function
End Class
```



```
interface:
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Runtime.Serialization

' NOTE: You can use the "Rename" command on the context menu to change the interface name "IVSAPIAJAX" in both code and config file together.
<ServiceContract()>
Public Interface IVSAPIAJAX

    <OperationContract()>
    Sub DoWork()

    <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    <OperationContract()> _
    Function test() As String


End Interface
```



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

  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>      
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>              
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>      
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="VSAPIAJAX">
        <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="IVSAPIAJAX">
          <!--  <identity>
            <dns value="localhost" />
          </identity> -->
        </endpoint>        
      </service>         
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>
```



```
//Javascript

<script src="Javascript/jquery-1.11.2.min.js" type="text/javascript"></script>
 <script type="text/javascript">
     $(document).ready(function () {
         $.ajax({
             type: "POST",
             url: "http://localhost:15328/VSAPIAJAX.svc/test",
             data: "{}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (response) {
                 alert('d');
                 try {
                     var oRetVal = response.d;
                     alert(d);
                 }
                 catch (ex) {
                     alert(ex);
                 }
             },
             failure: function (msg) {
                 alert(msg);
             }
         });
         alert('error');
     });
     </script>
```

Have tried local iis and local website asp server.Cannot get anything. Is this so hard to call a WCF service outside a web site? 
Thanks

----------


## sapator

get 404 not found with this:


```
 $(document).ready(function () {
        

             $.ajax({
                 dataType: 'jsonp',
                 contentType: "text/json; charset=utf-8",
                 data: "",
                 url: "http://localhost/vsapiajax.svc/test",
                 success: function (response) {
                     var innerHtml = "";
                    alert('d');                     

                 }
             });
         
         alert('error');
     });
```

When i go to http://localhost/vsapiajax.svc i can see the service. When i go to http://localhost/vsapiajax.svc/test i get a blank page but there are no errors presented in the browser.

----------


## Lightning

You should add the _ScriptService_ directive to the operation-name

----------


## sapator

Hi.
Have you actually succeed in running a site?
Nothing seems to work for me.
I've added - removed  and made combinations but nothing works.
Here is all the stuff i add and remove:


```
<System.Web.Script.Services.ScriptService()> _
<ServiceContract()>
 <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _  
Public Interface IVSAPIAJAX

    <WebMethod()> _
       <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
        <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    Function test() As String
```

Also read that maybe i need  CORS operations? But i have no idea how to do that and jsonp only works for get methods.

----------


## NeedSomeAnswers

You need Szlamany he's a big JavaScript / Json user !

unfortunately all my web service are consumed by C# code not JavaScript and so while they work on the local host (which shows they can be consumed) i cant be of much help  :Frown:

----------


## sapator

I'm not sure Szlamany uses WCF at all, he despise it  :Smilie:   I probably need sapator here but as you can see sapator has the issue. 
I can consume WCF with JS in a web site - application that hosts the wcf inside the website but i cannot , for the life of me, consume it as stand alone.
I think this is either a CORS issue (don't have a clue how to run POST requests and not only GET), a web.config issue or a webservice issue on the public interface class.
I have not found anything on the web. It's like everryone is making a website to call the WCF but that is not my intention here as I need this to be called not only from the website itself.

----------


## szlamany

Where is this being executed from?  Not in a browser from what I believe you are saying - right?

----------


## szlamany

Or is it just that you have never run a local IIS setup??

----------


## sapator

asp.net web site just to host the javascript and I tried to execute in Local IIS, IIS Express and in asp.net - visual studio self created IIS.
Hmm, let me clarify better. The WCF application is hosted in all IIS possible combinations except a remote IIS and the web site tried to call the web application methods - services with the usual Jquery - Json calls.
Will work if i host the WCF inside a web site - application and i get a breakpoint hit. Will not work if I host it as a stand alone WCF app but will work if i call it with server side methods ( that I do not want to do because I would have to have a server sided web side a.k.a. - Yack, hate MVC etc...)

----------


## szlamany

This is the way I specify a URL for a $.ajax POST



```
$.ajax({
    type: "POST",
    url: "WebService.asmx/SourceService",
    dataType: "json",
    data: strWebParam,
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        ajaxAsyncFinished(msg, strNewAccordion, "success", options);
    },
    failure: function(msg) {
        ajaxAsyncFinished(msg, strNewAccordion, "failure", {});
        $("#" + strNewAccordion).val("Loading...failure...");
    },
    error: function(msg) {
        ajaxAsyncFinished(msg, strNewAccordion, "error", {});
        $("#" + strNewAccordion).val("Loading...error...");
    }
});
```

So yours would be

url: "VSAPIAJAX.svc/test",

----------


## sapator

I do not think that this will work for IIS calls. Especially for calls outside of my local PC space,even if the domain is the same. If the WCF is on 192.168.101.20 and I am on 192.168.101.30 then I do not think the above will work.

----------


## sapator

I get not found with your url (seems logical) and with a specified IIS url i get:
XMLHttpRequest cannot load http://localhost/vsapiajax/vsapiajax.svc/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:13682' is therefore not allowed access. The response had HTTP status code 400. 
CORS issue?

http://localhost/VSAPIAJAX/vsapiajax.svc will show the services /test will show a blank page but no error. Not sure if it sees the service.

----------


## sapator

http://localhost/VSAPIAJAX/vsapiajax.svc/test will show 400 bad request on firebug.
Fiddler will also show 400 bad request.
Is this a web.config thing. I have also tried basichttpbinding with no avail. What the? Is this not supported on WCF? I can only call inside an app?
When i open the service console i am getting the value back from test. 
This may be beyond the ajax call as i will get 400 bad request simply by calling the service (/test) in a browser.

----------


## NeedSomeAnswers

> I probably need sapator here but as you can see sapator has the issue.


lol thanks you for my morning Chuckle  :LOL: 




> I'm not sure Szlamany uses WCF at all, he despise it


Oh i maybe wrong but i thought he did use WCF for web services and just didnt use any ASP for front end dev!! Szlamany am i right or have i got that completely wrong?




> Will work if i host the WCF inside a web site


Ok so maybe something is getting lost in translation ... but

- WCF is used to build the WebService itself which should live in a WCF Service Application which is a project option in VS !!! 

Then with a standalone service you can then call that from any website you wish. 

This is how i do it, create the WCF Service, set the service up in IIS and set it runnig, call the service methods from my web app

Are you currently doing something else?

----------


## szlamany

> I do not think that this will work for IIS calls. Especially for calls outside of my local PC space,even if the domain is the same. If the WCF is on 192.168.101.20 and I am on 192.168.101.30 then I do not think the above will work.


My web methods DO RUN is IIS.

So why would you think this would not work for IIS?

Did you GET a PAGE from this URL previously and you are executing the AJAX call from with the confines of that PAGE that you started with??

AJAX calls want you to specify the SERVICE and FUNCTION within.  You cannot specify the FULL URL or cross domain problems come up.

Obviously in a browser you specify the whole URL.

----------


## szlamany

> Oh i maybe wrong but i thought he did use WCF for web services and just didnt use any ASP for front end dev!! Szlamany am i right or have i got that completely wrong?


I do not use WCF.

I've created my own web methods that I call from JS with AJAX.

Doesn't this just come down to JS and AJAX - and isn't the cross domain issue all about not being able to specify a full URL - instead just the SERVICE/FUNCTION name.

In my jQuery AJAX call I have this



```
url: "WebService.asmx/SourceService",
```

And in IIS I have this function.



```
Option Strict On
Option Explicit On

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Linq
Imports System.DirectoryServices.AccountManagement
Imports System.IO
Imports System.Diagnostics
Imports System.Object

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="AWCService")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)> _
    Public Function AddService(ByVal toddtype As String, ByVal fromddtype As String, ByVal fromwho As String _
                                          , ByVal choice As Integer _
                                          , ByVal objReturn As Dictionary(Of String, String) _
                                          , ByVal addkey As String _
                                          , ByVal sguid As String _
                                          , ByVal username As String) As String
```

----------


## NeedSomeAnswers

My service URI's look like this - 



```
private static readonly string webServiceUri = "http://localhost:57732/RestServiceImpl.svc/json";                    //Local
private static readonly string webServiceUri = "http://[servername]/DTOLRestService/RestServiceImpl.svc/json";       //Server
```

and the interface for my rest service looks like this - 



```
[ServiceContract]
    public interface IRestServiceImpl
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/{id}")]
        string JsonData(string id);
    }
```

if that's of any help

----------


## NeedSomeAnswers

> I do not use WCF.
> 
> I've created my own web methods that I call from JS with AJAX.


Ah so i was wrong, nevermind   :Smilie:

----------


## szlamany

The URI string doesn't tell you what the internal AJAX call is using for a URL.  Can you go into FireBug and see what was actually used?

The page has to LOAD before the SERVICE can be executed from what I know.

Does it work that way in WCF also?

----------


## sapator

> My web methods DO RUN is IIS.
> 
> 
> 
> AJAX calls want you to specify the SERVICE and FUNCTION within.  You cannot specify the FULL URL or cross domain problems come up.
> 
> Obviously in a browser you specify the whole URL.


Ok so how would I go about calling a service from another IIS but the local? Let's say I have the service in IIS on 192.168.100.20 and my computer is 192.168.100.30,
how would i call the WCF on JS? url =???  If i use just /vsapiservice/test then I am just calling something local. 
The example you give is simple webservice (saw the webmethod part  :Smilie:   ) I can't use simple webservices, not my call.

@Needsomeanswers have you tried using the WCF with Jquery?? As I've said I can call the service up down reverse and in full speed if i do it from server side code but not in Jquery.

----------


## NeedSomeAnswers

> @Needsomeanswers have you tried using the WCF with Jquery?? As I've said I can call the service up down reverse and in full speed if i do it from server side code but not in Jquery.


Ah no i have not sorry, all my calls are server side at the moment.

----------


## sapator

Ok. Can we unmix things here?
The WCF I am going to use will be on an IIS, somewhere in the domain. So the call should not be myservice/test but http://192.168.100.20/myservice/test . If that is not supported there is no way to call a remote IIS.
The WCF application host the WCF services. I do not know the exact mambo jumbo but calling it from Ajax will call the service, not a page load wait.I guess.
How will you call a web service on http://www.serverX/Webservice1/service1 ? obviously doing Webservice1/service1 will not work.
You need the full address..

----------


## szlamany

You have to execute an ajax call from within the confines of a page already loaded from that domain.

Otherwise it's cross domain and that's evil.

When I say DOMAIN it's the WWW domain I'm taking about - not just some other machine on a network.

----------


## szlamany

> Ah no i have not sorry, all my calls are server side at the moment.


It looks like JS code though in your WCF setup - right?

So that code is being pushed to the browser to execute.

Which is something do myself in other situations.

None of this changes the way the internal ajax is called.  It's just another MS layer on top of the real stuff

----------


## sapator

I'm calling this non possible until proven otherwise. There is not one valid and working example anywhere to be found on the web.

----------


## szlamany

Why would you think that WCF would get you the ability to cross domain post?

Your AJAX runs against the URL that you originally loaded the PAGE from.  Any FILE in that ROOT folder or SUB folder you can get to.

I AJAX to my web methods and also AJAX in IFRAMES to UPLOAD and DOWNLOAD pages.

What are you trying to achieve??

----------


## sapator

A simple example would be the yahoo weather API that i have used.
You call it with a webservice (not WCF though) and you get the data.
It's of course on another domain.

----------


## szlamany

With the same type of AJAX call?

Do you have the dev-iis environment fired up on the development machine you are connect to?

----------


## sapator

Same but WCF. The IIS is at my job, it's working fine as i can call WCF from with server calls.
I also have a remote (in the same domain) IIS that is hosting our test websites, so I can use that too on Monday.
I just need the service init calls (p.e. <aspcombatibility...etc>  one line return function and a correct web.config. After that I can take it from there and connect with Jquery. Jquery is not the issue here, i have created an entire site with AJAX and WCF but the damn WCF is inside the web site so i have no problems calling the methods.

----------


## sapator

Anyhow the general idea is to call a WCF service from AJAX from a web app (and WCF not being inside your app).
Probably won't get answers since i think no one has done something like this here but here goes: I am using CORS as it seems it is the only way to  call a WCF service outside your app.
I get an error and cannot configure <crossOriginResourceSharingBehavior /> and also it will not work on AJAX calls.
Get a load of this cr#p that we need in order for WCF to work(and after all these, still does not work.)!

web service:


```
' NOTE: You can use the "Rename" command on the context menu to change the interface name "IService1" in both code and config file together.
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
Imports System.ServiceModel
Imports System.ServiceModel.Web

<System.Web.Script.Services.ScriptService()> _
<ServiceContract()> _
Public Interface IService1

    ''<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    <WebGet(UriTemplate:="GetData", ResponseFormat:=WebMessageFormat.Json)>
   <OperationContract()> _
    Function GetData() As String
End Interface
```

web service.vb:


```
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
Imports System
Imports System.ServiceModel.Activation

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
    Implements IService1


    Public Function GetData() As String Implements IService1.GetData
        Return ("x")
    End Function
End Class
```

CORS: (aka Crap Of Reliable Software)...
Are you ready?!! 
I said are you ready?!!!!
GO!


```
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Configuration
Imports System.ServiceModel.Description
Imports System.ServiceModel.Dispatcher

Namespace CORSExample

    Public Class CORSEnablingBehavior
        Inherits BehaviorExtensionElement
        Implements IEndpointBehavior

        Public Sub AddBindingParameters(ByVal endpoint As ServiceEndpoint, ByVal bindingParameters As BindingParameterCollection) Implements System.ServiceModel.Description.IEndpointBehavior.AddBindingParameters

        End Sub

        Public Sub ApplyClientBehavior(ByVal endpoint As ServiceEndpoint, ByVal clientRuntime As ClientRuntime) Implements System.ServiceModel.Description.IEndpointBehavior.ApplyClientBehavior

        End Sub

        Public Sub ApplyDispatchBehavior(ByVal endpoint As ServiceEndpoint, ByVal endpointDispatcher As EndpointDispatcher) Implements System.ServiceModel.Description.IEndpointBehavior.ApplyDispatchBehavior
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(New CORSHeaderInjectingMessageInspector)
        End Sub

        Public Sub Validate(ByVal endpoint As ServiceEndpoint) Implements System.ServiceModel.Description.IEndpointBehavior.Validate

        End Sub

        Public Overrides ReadOnly Property BehaviorType As Type
            Get
                Return GetType(CORSEnablingBehavior)
            End Get
        End Property

        Protected Overrides Function CreateBehavior() As Object
            Return New CORSEnablingBehavior
        End Function

        Private Class CORSHeaderInjectingMessageInspector
            Implements IDispatchMessageInspector

            Public Function AfterReceiveRequest(ByRef request As Message, ByVal channel As IClientChannel, ByVal instanceContext As InstanceContext) As Object Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest
                Return Nothing
            End Function


            Private Shared _headersToInject As IDictionary(Of String, String) = New Dictionary(Of String, String)() From { _
             {"Access-Control-Allow-Origin", "*"}, _
             {"Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS"}, _
             {"Access-Control-Allow-Headers", "X-Requested-With,Content-Type"} _
            }

            Public Sub BeforeSendReply(ByRef reply As Message, ByVal correlationState As Object) Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply
                Dim httpHeader As Object = CType(reply.Properties("httpResponse"), HttpResponseMessageProperty)
                For Each item As Object In _headersToInject
                    httpHeader.Headers.Add(item.Key, item.Value)
                Next
            End Sub
        End Class
    End Class
End Namespace
```

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.0"/>
  </system.web>

  <system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add
          name="crossOriginResourceSharingBehavior"
          type="WcfService1.CORSEnablingBehavior, WcfService1, Version=1.0.0.0, Culture=neutral" />
      </behaviorExtensions>
    </extensions>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp />
      
          <!-- <crossOriginResourceSharingBehavior /> -->
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" />
      </service>
    </services>

  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
```

So anyhow if I ever find what the F is going on I will let you know and submit it in code data as I would probably be the first to ever pull this off in VB.

----------


## sapator

Managed to make it use GET! Cannot use POST though. Sap please help! :P


```
  Public Function GetData() As String Implements IService1.GetData
        'for all cors requests  
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*")
        'identify preflight request and add extra headers  
        If WebOperationContext.Current.IncomingRequest.Method = "OPTIONS" Then
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET")
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, x-requested-with")
            Return Nothing
        End If
        Return "Hello!"
    End Function
```



```
' NOTE: You can use the "Rename" command on the context menu to change the interface name "IService1" in both code and config file together.
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
Imports System.ServiceModel
Imports System.ServiceModel.Web

<System.Web.Script.Services.ScriptService()> _
<ServiceContract()> _
Public Interface IService1




    '<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
        <WebGet(UriTemplate:="GetData", ResponseFormat:=WebMessageFormat.Json)>
   <OperationContract()> _
    Function GetData() As String
End Interface
```

----------


## sapator

OK. This is supposed to work but  it does not. It will give 200 ok but will never get to the function, only go to the error clause.
Maybe I'm using something wrongly. Anyone take a look, at least to verify that I haven't done something wrong?
Thanks.
Service1.svc


```
Imports System.ServiceModel.Activation

' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
    Implements IService1

    Public Sub New()
    End Sub



    <WebInvoke(Method:="POST", RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/GetMedicalHistory")>
    Function GetMedicalHistory() As String Implements IService1.GetMedicalHistory
        Return "x"
    End Function
End Class
```

Used inside Global.asax now:


```
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost")
        If HttpContext.Current.Request.HttpMethod = "OPTIONS" Then
            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()
        End If
        ' Fires at the beginning of each request
    End Sub
```

IService1.svc


```
' NOTE: You can use the "Rename" command on the context menu to change the interface name "IService1" in both code and config file together.
<System.Web.Script.Services.ScriptService()> _
<ServiceContract()>
Public Interface IService1


    ' TODO: Add your service operations here
    <OperationContract()>
    Function GetMedicalHistory() As String

End Interface
```

web.config:


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

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    <services>
      <service behaviorConfiguration="Default" name="WcfService1.Service1">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfService1.IService1" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
      </service>
    </services>
    <behaviors>

      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>      
      </serviceBehaviors>
    </behaviors>
 
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>
```

default.aspx calling page (from another web site app):


```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="javascript/jquery-1.11.2.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function () {
             getMedicalHistory();
         });

         function getMedicalHistory() {
             var User = 100;
             var data = { UserID: User };

             $.ajax({
                 url: 'http://localhost:45156/Service1.svc/GetMedicalHistory',
                 type: 'POST',
                 data: '{}',
                 dataType: 'json',
                 contentType: "application/json; charset=utf-8",
                 success: function (res) {
                     alert('ok');
                     console.log("Success");
                     console.log(res);
                     $('#result').html(res.d);
                 },
                 error: function (res) {
                     alert(res.statusText);
                     console.log("Error! " + res.statusText);
                 }
             });
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
```

----------


## sapator

Page error specifies:
XMLHttpRequest cannot load http://localhost:45156/Service1.svc/GetMedicalHistory. The 'Access-Control-Allow-Origin' header has a value 'http://localhost' that is not equal to the supplied origin. Origin 'http://localhost:45432' is therefore not allowed access.
Not sure how to change the global.asax localhost or the Ajax call so it can work. It's out of my field all these cross domain stuff..

----------


## szlamany

So I would imagine you have exhausted these links?

Google for:  access-control-allow-origin wcf service

Like this first link??

http://enable-cors.org/server_wcf.html

----------


## sapator

I've used this, you can see it on an above example.
The last example will give me 200ok Method:Options but will give the XMLHttpRequest error. I'm thinking that I am missing 1-2 lines but I have tried this 100 times and one thing works, another fails. 
The closet I got was the last example but I do not have a clue on why "localhost" fails. I've also use localost:45156 that is the WCF opening site to no avail.

----------


## szlamany

No one here is a WCF expert and you cannot find a better resource out there?  Any WCF books or whitepapers on this?

Did you say this worked in production and just not on your test box with localhost??

Have you tried the other tool for developing IIS - that Cassini thing??

----------


## sapator

I've use Cassini and localhost.
Use localhost:somenumber, localhost, mydomain. Nothing will bypass the might CORS!
All hail CORS the mighty firewall!

----------


## sapator

Did IT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
GOD DAM##$$# SH#$#$ FUC@##$!#@$@#$@# #$#$ $!!!!  !!!!
Used Access-Control-Allow-Origin", "*" , so it had to allow everything. I know this is not the best solution but for now I have a base to contact some test.
Oh my god! 3 days for a @#$^% "*" ! Deep inside i know it would be one line issue!

----------


## szlamany

MS bloat - WCF - isn't that what it really is?

----------


## sapator

I wish i could use simple web services as the configuration takes a lot more than the actual deployment but in order to be using company to company same methodology I am force to use the damn thing.
I am looking on suggesting web API this is supposed to be "easier" to set up but it only takes one parameter on "POST" and you have to do "stuff" in order to make that parameter to a lot of parameters. I mean what is wrong with MS ? MVC, Web API cut down? What's next, a windows phone!?....Oh wait...

----------


## sapator

A basic example submitted to codebank so you won't lose you time searching for this:
*http://www.vbforums.com/showthread.p...d-CORS-enabled*

----------


## sapator

Seems that this is also true for simple asp.net web services and not only WCF. 
OK 2000 years later but It helped me at once, as the server event viewer wasn't returning any errors. All OK SAP,go for it, Yo, Yo, check this out, no error man!
All OK but I could not return nada from a fully working local web service.
So good 2 birds in one stone.
Let me write that in code bank also....

----------

