1

I am attempting to connect to a WCF web service with Ionic4. I can connect to the web service using regular ajax but I cannot with Ionic's HTTPClient. The error that I am receiving is that the webservice is not configured to accept connections from the server.

Below is the code from the web server that is set to accept connections from foreign servers. The other section of code is the connection to the webserver from the Ionic application.

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

constructor(private http: HttpClient) { }

query() {
  this.data = this.http.get('http://localhost:55283/LOAService.svc/test');
  this.data.subscribe(data => {
    this.result = data;
  });
}
}

As I can connect from ajax I can only assume that the problem is with the Ionic code. Am I right to assume this?

Alex Wynet
  • 11
  • 3

1 Answers1

0

There is no problem with WCF cross-domain configuration in your code snippet. How do you publish your service? if you want to access the service with Angular httpclient library, I suggest you publish it in restful style.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/wcf-and-aspnet-web-api
How can I use a WCF Service?
I have made a demo, wish it is useful to you(Since you have posted about cross-domain configuration, I used another configuration.but they are similiar).
Wcf service(interface and implementation)

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebGet(ResponseFormat =WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json)]
        string GetData(int value);
}
public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
}

Web.config

    <system.serviceModel>
        <services>
          <service name="WcfService2.Service1">
            <endpoint address="" binding="webHttpBinding" contract="WcfService2.IService1" behaviorConfiguration="myBehavior"></endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
          </service>
        </services>
        <behaviors>
          <endpointBehaviors>
            <behavior name="myBehavior">
              <webHttp />
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior>
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*"/>
      <add name="Access-Control-Allow-Headers" value="content-type" />
      <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
    </customHeaders>
  </httpProtocol>  

global.asax.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.End();
            }
}

Client(App.component.ts)

import { Component,OnInit } from '@angular/core';
import {HttpClient,HttpHeaders} from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my angular';
  data='';
  private url="http://10.157.18.36:12000/service1.svc/getdata?value=100"
  constructor(
    private http: HttpClient
  ){

  }
  getData():Observable<string>{
    return this.http.get<string>(this.url,{responseType:'json'});
  }
ngOnInit(){
  this.getData().subscribe(x=>this.data=x);
}
}

Client(App.component.html)

<div style="text-align:center">
  <h1>
    {{ title }}!
  </h1>
</div>
<hr>
{{data}}

Result.
enter image description here
Feel free to let me know if there is anything I can help with.

Abraham Qian
  • 7,117
  • 1
  • 8
  • 22