WCF service shows empty screen on browser

Question!

I have a test WCF service, when I try this on visual studio it works fine, when I paste the link http://localhost:1347/Service1.svc/DoWork in the browser it shows bad request with empty white screen of the browser

Failed to load resource: the server responded with a status of 400 (Bad Request)

When I tried with JSON it shows CORS issue, I added some script in Web.Config but still exist the problem of bad request, WCF has following operation contracts;

namespace WcfService1
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string DoWork();

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);


    }
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

their implementation comes here.

public class Service1 : IService1
    {

        public string DoWork()
        {
            return string.Format("This is DoWork()");
        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

Web.Config

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

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>

    <!--
        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"/>
    <validation validateIntegratedModeConfiguration="false"/>




  </system.webServer>

</configuration>

JSON call

$(document).ready(function(){
            $.get("http://localhost:1347/Service1.svc/DoWork", function(data, status){

                alert("Data: " + data + "\nStatus: " + status);
        });


Answers
Add following code in your global.asax file. This will allow preflight requests to complete successfully.

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("Access-Control-Allow-Methods", "GET, POST");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    HttpContext.Current.Response.End();
    }
}
By : Leopard


The "bad request" responses would be due to the HTTP verb mismatch. SOAP requests for all operations with basicHttpBinding in WCF use HTTP POST, not HTTP GET. If you want to use HTTP GET, use webHttpBinding.

Or better still, use Web API instead of WCF.



This video can help you solving your question :)
By: admin