I have a WCF service that works when hosted on my local machine but does not work when hosted with IIS on the server.
An unhandled communication exception is thrown
. "An error occurred while receiving the HTTP response to {url}. This
could be due to the service endpoint binding not using the HTTP
protocol. This could also be due to an HTTP request context being
aborted by the server (possibly due to the service shutting down). See
server logs for more details."
The inner exception is
"The underlying connection was closed: An unexpected error occurred on
receive."
I have enabled tracing but to my fault I can't really find anything I can see in there that has helped me. Also, I have seem other threads regarding this issue but nothing has seemed to help.
The server is using https I can't help but think that this is the problem. When I run it locally using http. Everything works correctly.
These calls are retrieving very large amounts of data but I can't help that.
Could anyone please help me with this?
Web.Config
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="2147483647" executionTimeout="2147483647"/>
</system.web>
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="false" logMessagesAtServiceLevel="false" logMessagesAtTransportLevel="true" maxMessagesToLog="3000" maxSizeOfMessageToLog="2000"></messageLogging>
</diagnostics>
<services>
<service name="Logistics.Wcf.LogisticsService" behaviorConfiguration="serviceBehavior" >
<endpoint address="soap" binding="basicHttpsBinding" contract="Logistics.Wcf.ILogisticsService"></endpoint>
<!--<endpoint address="rest" binding="webHttpBinding" contract="Logistics.Wcf.ILogisticsService" behaviorConfiguration="restBehavior"></endpoint>-->
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<!-- 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"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpsBinding>
<binding name="basicHttpsBinding"
closeTimeout="00:15:00"
openTimeout="00:15:00"
receiveTimeout="00:15:00"
sendTimeout="00:15:00"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
>
<security>
<transport clientCredentialType="None"></transport>
</security>
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpsBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<validation validateIntegratedModeConfiguration="false" />
<!--
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"/>
</system.webServer>
<connectionStrings>
<add name="LogisticsEntities" connectionString="metadata=res://*/LogisticsModel.csdl|res://*/LogisticsModel.ssdl|res://*/LogisticsModel.msl;provider=System.Data.SqlClient;provider connection string="data source=hertz1105\devl;initial catalog=Logistics;user id=airclic2;password=air123_***;connect timeout=6000;applicationintent=ReadWrite;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing">
<listeners>
<add name="log" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Traces.scvlog"></add>
</listeners>
</source>
</sources>
<trace autoflush="true"></trace>
</system.diagnostics>
Contract:
[OperationContract]
[WebGet(UriTemplate = "/GetDeliveryInstructions?authenticationToken={AUTHENTICATIONTOKEN}&countryCode={COUNTRYCODE}&beginDate={BEGINDATE}&endDate={ENDDATE}", ResponseFormat = WebMessageFormat.Xml)]
List<DeliveryInstruction> GetDeliveryInstructions(string authenticationToken, string countryCode, string beginDate, string endDate);
Service Method:
public List<DeliveryInstruction> GetDeliveryInstructions(string authenticationToken, string countryCode, string beginDate, string endDate)
{
try
{
if (AuthenticationTokenValidator.IsValidToken(authenticationToken))
return DeliveryInstructionAdministrator.GetList(countryCode, beginDate, endDate).ToList();
else
throw new InvalidOperationException("Your token is invalid or expired.");
}
catch (FaultException<TimeoutException>)
{
return DeliveryInstructionAdministrator.GetList(countryCode, beginDate, endDate).ToList();
}
catch (FaultException faultException)
{
WebServiceExceptionLog logEntry = new WebServiceExceptionLog(faultException, "Logistics.Wcf", "GetDeliveryIntructions", faultException.GetType().ToString(), authenticationToken);
ExceptionLogger.LogException(logEntry);
return null;
}
catch (CommunicationException communcationException)
{
WebServiceExceptionLog logEntry = new WebServiceExceptionLog(communcationException, "Logistics.Wcf", "GetDeliveryIntructions", communcationException.GetType().ToString(), authenticationToken);
ExceptionLogger.LogException(logEntry);
return null;
}
}
* UPDATE *
The problem is with Entity Framework. I am using Entity Framework to retrieve POCO entities. Still not sure how to fix it though.
You should enable wcf logging on you server. However I have seen this error when the maxRequestLength was not set correctly in the web.config and the incoming messages where large:
<system.web>
<httpRuntime maxRequestLength="10000" />
</system.web>
Enable tracing:
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
Tracing WCF
Related
I have a WCF service application set up so when I call the address it just returns true.
IRemoteService.cs
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "ValidationResult/")]
bool ValidationResult();
RemoteService.svc.cs
namespace RemoteService
{
public class RemoteService : IRemoteService
{
public bool ValidationResult()
{
return true;
//throw new NotImplementedException();
}
}
}
I have added an application on IIS and now I can access the service on the following url :
https://localhost/ValidationServiceApp/RemoteService.svc/validationresult/
This returns :
{"ValidationResultResult":true}
Works great. But when I run the following powershell script, I cant access the service :
$url = "https://localhost/ValidationServiceApp/SASRemoteService.svc/validationresult/"
$result = Invoke-RestMethod -Method GET -Uri $url
Write-Host $result
I must point out, I have tried on a client application called 'I'm only resting' and this returns whats expected. So I think it must be something to do with powershell. Either I haven't allowed something in the web.config file or some setting missing in powershell. I have also tried to ignore certificate errors on powershell. This didn't help.
Error from powershell :
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:18 char:11
+ $result = Invoke-RestMethod -Method GET -Uri $url
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Here is the web.config file for the service :
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="RemoteService.RemoteService" behaviorConfiguration="ServiceBehaviour">
<endpoint address =""
binding="webHttpBinding"
contract="RemoteService.IRemoteService"
bindingConfiguration="webHttpTransportSecurity"
behaviorConfiguration="web" />
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="false" 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>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" 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>
<!--
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>
Managed to find the problem.
I needed to edit permissions on the hosted service in IIS. So I added Users ({pcname}/Users) to the list of allowed users.
I would delete the question, but perhaps this may help someone in the future :)
I create a client application that get data from my rest wcf service as you can see :
Uri reqUri = new Uri("https://localhost/paymentservice.svc/listpayment");
WebRequest req = WebRequest.Create(reqUri);
req.PreAuthenticate = true;
NetworkCredential credential = new NetworkCredential("test", "test123");
req.Credentials = credential;
WebResponse resp = req.GetResponse();
DataContractSerializer data = new DataContractSerializer(typeof(string));
var res = data.ReadObject(resp.GetResponseStream());
Console.WriteLine(res);
Console.ReadLine();
I create a certificate in iis as you can se :
And upload my published file on it .
But when i call my client i get this error :
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
Here is my service webconfig
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<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>
<authentication mode="None" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Payment.Application.ServiceImplement.PaymentService" behaviorConfiguration="customBehaviour">
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Service.IPaymentService"
behaviorConfiguration="web"/>
</service>
<service name="Payment.Infrustructure.RepositoryImplement.PaymentRepository" behaviorConfiguration="customBehaviour" >
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Repository.IPaymentRepository"
behaviorConfiguration="web"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="customBehaviour">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="Payment.Service.UserAuthentication,Payment.Service"/>
</serviceCredentials>
<!-- 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>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="GET, POST,PUT,DELETE" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<!--
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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;initial catalog=SymfaDB;user id= sa ;password=12345;" providerName="System.Data.SqlClient" />
<!--<add name="DefaultConnection" connectionString="Data Source=92.50.12.222,1433;initial catalog=ParkingDB;user id= sa ;password=123qweQWE#;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
</configuration>
When irun the project in visual studio and call this url http://localhost:4428/PaymentService.svc/listpayment I get the data as you can see :
But when i upload the publish file into iis and call this url https://localhost/PaymentService.svc/listpayment as you can see i get this error :
As you can see when i call this https://localhost/PaymentService.svc my service is available .
You need to install the certificate as trusted source.
Open a command prompt with admin rights, type "mmc" and press enter which will open Microsoft Management Console.
From Menu go to File > Add/Remove Snap-In, select Certificates and Click Add
Select Computer Account and click Next, select Local Computer and click Finish.
Go to Certificates (Local Computer) > Personal > Certificates
From the Menu go to Action > All Tasks > Import
Click Next in the Certificate Import Wizard, Provide the path to the certificate file, enter the password if any then click Next, Next and Finish.
Now you will be back to Microsoft Management Console, click on Trusted Root Certification Authorities, select Certificates, Action > All Tasks > Import and follow the step 6.
Also the hostname used in the URL should match the name that's on certificate. Make sure the URL you're using and the URL on the 'Issued to' field of the certificate are the same.
To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. For example, if you open your certificate then you’ll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like .. etc, so if you open it in your browser will fully qualified name of your machine then you won’t be getting that error.
So i just call my service by domain like https://union-pc58.union.com/Service1.svc
Just follow this link
http://www.c-sharpcorner.com/UploadFile/vendettamit/create-secure-wcf-rest-api-with-custom-basic-authentication/
I have created the WCF service and consumed that service into my client side application and I'm unable to invoke the method.
the following exception is occured:
{"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs."}
I think there is the some issue with the binding. I had googled but didn't find any solution. Please guide me how can I fix this issue. Help will be appreciate.
Thanks
Code Snippet:
Service 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.5"/>
</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"/>
<!--
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"/>
</system.webServer>
</configuration>
Index.aspx
private void process()
{
TestRef.EmployeeDC o = new TestRef.EmployeeDC();
o.userID = signInEmail;
o.companyID = signInPassword;
//ServiceReference.EmployeeDC p = new ServiceReference.EmployeeDC();
//Service Call
TestRef.TestServClient tsc = new TestRef.TestServClient();
tsc.callBusinessLayer(o); // here im getting the exception
Debug.Print(""+signInEmail);
}
Client Side Web.Config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITestServ" />
<binding name="BasicHttpBinding_ITestServ1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/Publish/TestServ.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITestServ" contract="ServiceReference.ITestServ"
name="BasicHttpBinding_ITestServ" />
<endpoint address="http://localhost/Publish/TestServ.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITestServ1" contract="TestRef.ITestServ"
name="BasicHttpBinding_ITestServ1" />
</client>
</system.serviceModel>
</configuration>
I have a WCF which I get the
"The remote server returned an unexpected response: (400) Bad Request."
error just in calling a specific Method of it.
This is web.Config in server side
<configuration>
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="CableContext" connectionString="metadata=res://*/CableModel.csdl|res://*/CableModel.ssdl|res://*/CableModel.msl;provider=System.Data.SqlClient;provider connection string="data source=pgdbserver;initial catalog=CableDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
and this is the app.config in client side
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="UserManager" value="http://appserver:8080/SecurityServices/UserManager.asmx" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ICableService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="9830400" maxBufferPoolSize="524288" maxReceivedMessageSize="9830400" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="64" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://appserver:8080/CableDataService/CableService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICableService" contract="CableServiceReference.ICableService" name="BasicHttpBinding_ICableService" />
</client>
</system.serviceModel>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
</configuration>
and this is the code I am Calling
public int Export(Cable cableToSave )
{
int result = 0;
using (UnitOfWork unitOfWork = new UnitOfWork())
{
if (cableToSave.CableProperty != null && cableToSave.CableProperty.CableApplication != null && cableToSave.CableProperty.CableApplication.State == State.Added)
{
cableToSave.CableProperty.CableApplication.CableProperties = null;
unitOfWork.CableApplicationRepository.Insert(cableToSave.CableProperty.CableApplication);
}
if (cableToSave.CableProperty != null && cableToSave.CableProperty.State == State.Added)
{
cableToSave.CableProperty.Cables = null;
unitOfWork.CablePropertyRepository.Insert(cableToSave.CableProperty);
}
if (cableToSave.State == State.Added)
{
unitOfWork.CableRepository.Insert(cableToSave);
result = cableToSave.Id;
if (cableToSave.Cores != null)
foreach (Core coreToSave in cableToSave.Cores)
{
unitOfWork.CoreRepository.Insert(coreToSave);
}
}
unitOfWork.Save();
return result;
}
}
An error code beginning with 4xx (that is, four-hundred-something) means that the problem is with the data you're sending to the server - the server can't understand the data you're sending. For example, if the request expects an integer parameter but you send a string, you'll see this problem.
(By contrast, a 5XX error means that the server understood your request, but threw an error during the processing.)
Often, a 4xx error in a WCF service means that the request isn't even reaching your code, because it may be that WCF can't deserialize the data you're sending into the types required to call your methods. In this case, if you're posting data that isn't a valid Cable, you'll see a 400 error without your code ever being called.
You can test this by examining the requests that you're sending, and also by writing a small test harness (I recommend using Linqpad!) to deserialize your request body manually - you may find the cause of your issue there.
You'll probably need to turn on the WCF logging to figure this out. The logging will show you the content of the inbound request, plus your service's reaction to it. Based on that, you should be able to figure out the problem.
Here's a link to the "how to"
I'm new to writing questions, long time reader. If I omit something please let me know.
I have looked through many different scenario's and possible fixes and have been unable to get my WCF Service working correctly.
My service is responsible for passing data from many different sets to a master repository. The client gathers the data at the local set level and passes it to the service which inserts the data and passes back a result message. Again in the test environment this worked normally.
In production I added the service to an off-site server and configured the client on a remote set. The client was able to configure and receive updates from the service. Up until now everything worked correctly. However once the client attempted to transfer data across it received the following error "Object reference not set to an instance of an object."
Through bug checking I have confirmed there are no connection string issues to the db. I ran the same data transfer again in my test environment with no issues. I was able to connect to the .svc url on the local set.
I've added logging at different points through the data contract method call and none of these logs have triggered any results. I've also tested the write functionality on a test app which confirmed there were no issues with credentials writing to the temp folder. Eg:
public Result InsertVenueRecord(Venue v)
{
System.IO.File.WriteAllText(#"C:\temp\MadeItToVenue" + DateTime.Now.Ticks.ToString() + ".log.txt", "insertVenue()\r\n\r\n");
int oldId = v.VenueId;
try
{
System.IO.File.WriteAllText(#"C:\temp\MadeItToVenue" + DateTime.Now.Ticks.ToString() + ".log.txt", "insertVenue()\r\n\r\n");
//Check Address
if (v.Address.AddressId != 0)
The client app.Config looks as follows:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_placeholder" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="Removed" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_placeholder" contract="placeholder.placeholder"
name="BasicHttpBinding_placeholder" />
</client>
</system.serviceModel>
<appSettings>
<add key="DTFirstWave" value="Venue|Event|EventSurveyLocation|Agent|LoginHistory|LoginUsed"/>
</appSettings>
<connectionStrings>
<!-- Removed Connection Strings -->
</connectionStrings>
</configuration>
The service webconfig looks as follows:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding allowCookies="true" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="52428800" maxArrayLength="52428800" maxBytesPerRead="52428800" maxNameTableCharCount="52428800"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<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>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
<connectionStrings>
<!--Removed -->
</connectionStrings>
</configuration>
I'm at a loss as to why this isn't working.
plz enable your service SVC log by just add system.daignostics in your service config.It will give you proper error on production.
It will create "App_tracelog.svclog" file in your service dir.
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.Runtime.Serialization" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="App_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp" />
</sharedListeners>