0

I am having trouble while sending the request to a rest service. The service works fine on my desktop, but getting the following error when i host on the IIS.

HTTP/1.1 400 Bad Request when i use https

HTTP/1.1 404 Not Found when i use http

Here is my web.config

<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service     
behaviorConfiguration="CoreService.DialService.DialServiceBehavior" 
name="CoreService.DialService.TelephonyService">
<endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding" 
bindingConfiguration="webBinding" 
contract="CoreService.DialService.ITelephonyService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors> 
<behavior name="CoreService.DialService.DialServiceBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
multipleSiteBindingsEnabled="true"/>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true" 
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" 
maxMessagesToLog="3000" maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>

Service Contract

[WebInvoke(UriTemplate = "/Dial", Method = "POST", RequestFormat = 
    WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    Objects.Response.Telephony.DialResponse 
    Dial(Objects.Request.Telephony.DialRequest request);

Here is the client

DialRequest DialRequest = new DialRequest();
DialResponse DialResponse = new DialResponse();

DialRequest.ProjectID = "AMS0103300";
DialRequest.DialFromExtension = "1234";
DialRequest.OutDialCode = "51";
DialRequest.RequestBy = "HC User";
DialRequest.DialToPhoneNumber = "1234567890";
DialRequest.RequestDate = DateTime.Now;
DialRequest.ApplicationID = Guid.Parse("F5EE534B-B5ED-4ADD-B671- 
CCF7C05057A7");


DataContractJsonSerializer ser =
new 
DataContractJsonSerializer(typeof(Objects.Request.Telephony.DialRequest));

MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, DialRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);

WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;


var result = webClient.UploadString("https://test.xxxx.com/DialService/TelephonyService.svc/Dial","POST", data);

I have tried with different values in protocolMapping, but the results are same. Any help will be appreciated.

chintpal
  • 1
  • 1

1 Answers1

0

It seems to me that there are no errors in you project. Besides protocol mapping is the new feature in Net4.5, which could help us simplify settings.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/simplified-configuration
How to make WCF Service Use HTTPS protocol
There might be some small problems during the process of hosting the service on the IIS. Could you access the WSDL page successfully? Like the following form. enter image description here We might need to enable the WCF feature in the control panel. https://i.stack.imgur.com/ivP92.png
I have made an example, wish it is useful to you.
Server-side (WCF service application).
IService1

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebGet]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        [OperationContract]
        [WebInvoke(UriTemplate ="/MyTest",Method ="POST",RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]
        string Test(CompositeType compositeType);
}
    [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; }
        }

        public override string ToString()
        {
            return $"The BoolValue is {boolValue}, StringValue is {stringValue}";
        }
    }

Service1.svc.cs

public class Service1 : IService1
{
    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;
    }

    public string Test(CompositeType compositeType)
    {
        return compositeType.ToString();
    }
}

Web.config

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="mybinding">
          <security mode="Transport">
            <transport clientCredentialType="None"></transport>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http"/>
      <add binding="webHttpBinding" scheme="https" bindingConfiguration="mybinding"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

IIS(new website)
enter image description here
Client(generate the data contract by adding service reference)

static void Main(string[] args)
        {
            //for validating the self-signed certificated.
            ServicePointManager.ServerCertificateValidationCallback += delegate
              {
                  return true;
              };
            ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType()
            {
                StringValue = "Hello",
                BoolValue = true
            };
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceReference1.CompositeType));

            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, composite);
            string data = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);

            WebClient webclient = new WebClient();
            webclient.Headers["Content-type"] = "application/json";
            webclient.Encoding = Encoding.UTF8;
            var result = webclient.UploadString("https://localhost:8734/service1.svc/MyTest", "POST", data);
            Console.WriteLine(result);

            WebClient webclient2 = new WebClient();
            webclient2.Headers["Content-type"] = "application/json";
            webclient2.Encoding = Encoding.UTF8;
            var result2 = webclient2.UploadString("http://localhost:8733/service1.svc/MyTest", "POST", data);
            Console.WriteLine(result2);

        }

Result.
enter image description here
Besides, PostMan is good choice to test Rest style service. Feel free to let me know if the problem still exists.

Abraham Qian
  • 7,117
  • 1
  • 8
  • 22
  • Hi Abraham, Thank you for your response. Yes, i can access the wsdl without any issues. I am not sure what is wrong with my config. – chintpal Apr 16 '19 at 18:35
  • After you published the service on the IIS, could you access the other operations decorated by the [WebGet] in the browser? if not have a Get operation, try to add one for testing the service. – Abraham Qian Apr 17 '19 at 03:19
  • Update: I was able to access the other methods, but the only problem is while sending json request. I would appreciate your help. – chintpal Apr 25 '19 at 19:10
  • try to use my configuration, and publish it again. If it happened to bad request, try to check the request entity. At last, I suggest you check whether the request is being processed properly by coming into Debug mode. – Abraham Qian Apr 26 '19 at 03:22