Error 400 : invalid request on httpwebrequest - c#

I've built a WCF service that is hosted on a server by a windows service. Everything works fine and i have already tested some method. Now i need to send an httprequest from my client like this one:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(String.Format(#"http://192.168.0.170:9001/myServ/Start/{0}/{1}", "blabla", "blabla"));
req.Method = "GET";
The problem is that i keep getting an exception on client side stating that my request is invalid. I can't understand why.
This is my wcf service:
[OperationContract]
[WebInvoke(Method = "GET",
UriTemplate = "Start/{param1}/{param2}")]
string Mod(string param1, string param2);
Here is my configuration
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true"/>
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
sendTimeout="00:05:00"
name="WebHttpBinding_InotifyImp">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="wcfImp.notifyImp" behaviorConfiguration="NewBehavior">
<endpoint address="" behaviorConfiguration="DefaultEndPointBehavior" bindingConfiguration="WebHttpBinding_InotifyImp" binding="webHttpBinding" contract="wcfImp.InotifyImp">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:9001/notifyImp"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
<!-- 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="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="DefaultEndPointBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>

I found the problem. I was hosting my WCF service in debug mode using visual studio 2015 to check the various step of my process. I don't know why, but while i didn't have any problem with the other method, the handler associated to the get method, have an assembly that couldn't be loaded. I tried to host the service on windows service and everything worked fine

Related

An existing connection was closed by the remote host with WCF

I have developed WCF windows service using net tcp binding. Its working fine when wcf client and wcf service both are in domain (in two different system)
Getting error when both system are in work group not in domain.
Throwing an exception. Source: System.ServiceModel 4.0.0.0. Exception details: System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '04:59:59.7955781'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Things I tried:
Turned off Firewalls
Checked port
Increased the timeouts
First, you need to add windows credentials when requesting because nettcpbinding defaults to windows authentication:
ServiceReference1.CalculatorClient calculatorClient = new ServiceReference1.CalculatorClient();
calculatorClient.ClientCredentials.Windows.ClientCredential.UserName = "Administrator";
calculatorClient.ClientCredentials.Windows.ClientCredential.Password = "Password";
If you still have problems after adding credentials, you also need to add a mex endpoint:
<endpoint address="mex"
binding="mexTcpBinding"
contract="IMetadataExchange"></endpoint>
This is my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.serviceModel>
<services>
<service name="ConsoleApp5.CalculatorService" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:10234/GettingStarted/"/>
</baseAddresses>
</host>
<endpoint address="Test"
binding="netTcpBinding"
contract="ConsoleApp5.ICalculator"/>
<endpoint address="mex"
binding="mexTcpBinding"
contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
UPDATE
Set the Mode value to Message:
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
This is my App.config:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="Microsoft.Samples.X509CertificateValidator.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior">
<!-- use host/baseAddresses to configure base address provided by host -->
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8001/servicemodelsamples/service"/>
</baseAddresses>
</host>
<!-- use base address specified above, provide one endpoint -->
<endpoint address="certificate" binding="netTcpBinding" bindingConfiguration="Binding" contract="Microsoft.Samples.X509CertificateValidator.ICalculator"/>
</service>
</services>
<bindings>
<netTcpBinding>
<!-- X509 certificate binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata/>
<serviceCredentials>
<!--
The serviceCredentials behavior allows one to specify authentication constraints on client certificates.
-->
<clientCertificate>
<authentication certificateValidationMode="None" revocationMode="NoCheck"/>
</clientCertificate>
<!--
The serviceCredentials behavior allows one to define a service certificate.
A service certificate is used by a client to authenticate the service and provide message protection.
This configuration references the "localhost" certificate installed during the setup instructions.
-->
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Feel free to let me know if the problem persists.

HTTP Windows Service to HTTPS

I have a windows service that hosts my wcf service.
The app.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<system.serviceModel>
<services>
<service behaviorConfiguration="RestWCFServiceLibrary.Service1Behavior" name="RestWCFServiceLibrary.RestWCFServiceLibrary">
<endpoint address="" binding="webHttpBinding" contract="RestWCFServiceLibrary.IRestWCFServiceLibrary" behaviorConfiguration="web">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8888/RestWCFServiceLibrary/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="RestWCFServiceLibrary.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
<CorsSupport/>
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
</configuration>
My problem is that if I have my website using https:// it fails to make the http call because of CORS. The https website makes an ajax GET request to the localhost.
Now I am trying to change my windows service to https but everywhere I see some command line ssl bindings. Is there a different way I can change my wcf self hosted windows service to use https?
What do I need to do in order to get this http service migrated over to https.
Please provide example of what needs to be modified in my app.config.
I stumbled upon similar problem so what i did was used WCF Configuration tool to write a App.Config for me and inside endpoints I selected mexhttpsbinding and yaa the https binding worked..
Let's just add an https endpoint. The following configuration works properly over both http and https.
<system.serviceModel>
<services>
<service behaviorConfiguration="mybehavior" name="WcfService1.Service1">
<endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="webbev"></endpoint>
<endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="webbev" bindingConfiguration="myhttpsbinding"></endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"></endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:11010"/>
<add baseAddress="https://localhost:11011"/>
</baseAddresses>
</host>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="myhttpsbinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" sendTimeout="00:10:00" receiveTimeout="00:10:00">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" />
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="mybehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webbev">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
Since https protocol is protected by the certificate, we are supposed to bind the certificate to the https port for https endpoint. (we could specify the certificate in IIS binding module instead of CMD if hosting the service in IIS)
netsh http add sslcert ipport=0.0.0.0:11011 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF}
Execute CMD with administrator privileges and ensure that the certificate is installed on the local machine certificate store (certlm.msc). Certhash parameter specifies the thumbprint of the certificate. The appid parameter is a GUID that can be used to identify the owning application(located in the project.csproj file)
<ProjectGuid>{56FDE5B9-3821-49DB-82D3-9DCE376D950A}</ProjectGuid>
https://learn.microsoft.com/en-us/windows/desktop/http/add-sslcert
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-configure-a-port-with-an-ssl-certificate
Feel free to contact me if there is anything I can help with.
Https only works on port 443. so you better have your virtual host created in your SSL script tag in your server configuration.
Or you can also proxy pass your request http:// port(8888) to https:// (port:443)

c# wcf restful self hosted service closes connection / fails after too many requests

I have a self hosted WCF service, that should enable recording of some data that clients send.
(In my case, machines shall report done actions, that the service logs into one xml file for each machine, which is on the file system of the service host.)
For the file access there are global mutexes for each file.
The report method receives a stream, and processes that data until the file writing operations are done.
The problem is, that when I simulate the dataset reporting (1000-2000 reports, each client reports one dataset each 50-100ms, which is not a huge frequency I think) on multiple clients,
my wcf service connection sometimes seems to close (http response 400).
Furthermore the service throws Exceptions
Exception thrown: 'System.ServiceModel.CommunicationException' in System.ServiceModel.dll
Exception thrown: 'System.Net.HttpListenerException' in System.dll
and on the client side some Tasks (one task for each request) are getting canceled
Unhandled Exception: System.Threading.Tasks.TaskcanceledException...
Firstly I thought that the Problem is in the point of file accessing, but now
I think that the problem should be in the WCF Service configuration.
Because I removed the Methods processing (just return true), started 5 clients to 5000 requests at 50ms request frequency and the problem occured.
Here's my Service Configuration
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1"/>
</startup>
<!-- Webservice Configuration -->
<system.serviceModel>
<services>
<service behaviorConfiguration="Program.ServiceBehavior"
name="Program.HttpService.HttpService">
<endpoint address=""
binding="webHttpBinding"
bindingConfiguration="RestBinding"
contract="Program.HttpService.IFbmHttpService"
behaviorConfiguration="web">
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
name="MetadataEndpoint"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Program.ServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="RestBinding"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647">
<!--<readerQuotas maxStringContentLength="5242880" maxArrayLength="16384" maxBytesPerRead="4096" />-->
<security mode="None">
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel
<system.web>
<httpRuntime maxRequestLength="2000000"/>
</system.web>
<system.net>
<connectionManagement>
<add address="*" maxconnection="100"/>
</connectionManagement>
</system.net>
</configuration>

Problems with Hosting WCF service on IIS (Using WAS) for netTCP bindings?

I created a simple WCF service and hosted it in IIS by creating a new website. In Web.config file,I am providing bindings for http and net tcp.
I created a console client and adding service reference. It generates two binding in client config - for http and for tcp. When I try to invoke the service using tcp, I get this error -
An unhandled exception of type 'System.ServiceModel.EndpointNotFoundException' occurred in mscorlib.dll
Additional information: There was no endpoint listening at net.tcp://computername/Service.svc that could accept the message. This is often caused by an incorrect address or SOAP action.
when I run using Http endpoint , it works fine.
Note -
I am using Windows 10 OS, IIS 10.0 and WPAS\WAS (Windows Process Activation Service) are installed. I already enabled\checked HTTP Activation, TCP Activation in .Net framework in Windows features. And modified IIS server settings to include net tcp. Please check it in attached image.
My website Web.config file looks like
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NewBinding0" portSharingEnabled="true">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<services>
<service behaviorConfiguration="My" name="WCFServiceOM.Service1"> <!-- the service name must match the configuration name for the service implementation. -->
<endpoint address="" binding="basicHttpBinding" contract="WCFServiceOM.IService1"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<endpoint binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="WCFServiceOM.IService1" />
<endpoint address="mexOM" binding="mexTcpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8087/Service1" />
<add baseAddress="http://localhost:7777/Service1"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehanior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="My">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
And my client App.Config look like
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBinding_IService1">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="http://computername:7777/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
<endpoint address="net.tcp://computername/Service.svc" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IService1" contract="ServiceReference1.IService1"
name="NetTcpBinding_IService1" />
</client>
</system.serviceModel>

WCF Service: The remote server returned an unexpected response: (400) Bad Request

I have a WCF service which works great when small data has to be transferred over the wire. When I increase the data to a bigger size, I get following error:
The remote server returned an unexpected response: (400) Bad Request.
I know that this question has been asked many times be other user. But, I have tried all of those approaches to fix this issue. Nothing is working for me. Can you please have a look at my config contents and let me know if I am missing something. Following is my services' config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="RecieveValidationResultHubServiceLibrary.ReceiveValidationResultHubService">
<endpoint address="" binding="basicHttpBinding" contract="RecieveValidationResultHubServiceLibrary.IReceiveValidationResultHubService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8735/Design_Time_Addresses/RecieveValidationResultHubServiceLibrary/ReceiveValidationResultHubService/" />
</baseAddresses>
</host>
</service>
</services>
<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>
</system.serviceModel>
</configuration>
Following is service reference config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="MaxParallelThreads" value="300"/>
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IReceiveValidationResultHubService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8735/Design_Time_Addresses/RecieveValidationResultHubServiceLibrary/ReceiveValidationResultHubService/"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IReceiveValidationResultHubService"
contract="ReceiveValidationServiceReference.IReceiveValidationResultHubService"
name="BasicHttpBinding_IReceiveValidationResultHubService" />
</client>
<services>
<service name="StartValidationClientServiceLibrary.StartValidationClientService">
<endpoint address="" binding="basicHttpBinding" contract="StartValidationClientServiceLibrary.IStartValidationClientService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8734/Design_Time_Addresses/StartValidationClientServiceLibrary/StartValidationClientService/" />
</baseAddresses>
</host>
</service>
</services>
<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>
</system.serviceModel>
</configuration>
If error is about max reader quota, kindly make the change in web.config under your binding. See if it works.
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>

Categories

Resources