Unable to invoke method declared in WCF Service - c#

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>

Related

Connecting to WCF Rest Service Application from powershell not working as expected

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 :)

could not establish secure channel for ssl/tls with authority wcf C# wcf rest service

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/

How to make my CustomUserNamePasswordValidator work

I have been trying to get this working for hours now and have not had any luck. I am trying to create a WCF web service that has validation. I want the consumer of the service to be required to do:
ServiceReference1.XServiceClient client = new ServiceReference1.XServiceClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
before he can call any of the service methods. I found out that I have to create a CustomUserNamePasswordValidator so I created class library project in the solution to contain the Custom Validator class. I just wanted to verify that it works.
namespace XServices
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string username, string password)
{
if (!(username == "test" && password == "password"))
{
throw new FaultException("Invalid username or password!");
}
}
}
}
Then I tried to make the necessary changes to my web.config file in the WCF project to support it. Unfortunately, this is where I had my first trouble.
Here is my web.config file as it is now.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<!-- connection strings ommitted for security reasons -->
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</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>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator.XServices.CustomUserNameValidator, CustomUserNameValidator"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
The MSDN docs are very unclear on how the customUserNamePasswordValidatorType works. The example https://msdn.microsoft.com/en-us/library/aa702565(v=vs.110).aspx completely glosses over it so I have no idea if I even did it correctly. And worse, it does not throw an error if what you put for that parameter is incorrect. It just silently ignores it. Long story short, the Validate method of my custom validator is not being called. I can't figure out why and I haven't found anything that has worked after hours of google searching. Please help.
In your service config, you forgot to associate the serviceBehavior with your service. Therefore your service don't know anything about your custom validator.
The following section is missing:
<services>
<service behaviorConfiguration="CustomValidator" name="ServiceName...">
<endpoint name="EndpointName..." bindingConfiguration="Binding1" address="..." binding="wsHttpBinding" contract="..." />
</service>
</services>

WCF Webservice - Failed to invoke the service. The service is offline or inaccessible

We have developed the wcf service,when we are calling web service from WCF Test Client to fetch the data, In this case we are getting some exception while calling the WCF web service. I want to log error into html file.
My Code:-
try
{
int i = 1;
int j = 0;
int k = i / j;
}
catch (Exception ex)
{
ApplicationError.LogErrors(ex);
}
Web Config :-
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
</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 aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<remove name="ISAPI-dll"/>
<add name="ISAPI-dll" path="*.dll" verb="*" modules="IsapiModule" scriptProcessor="C:\WINDOWS\System32\inetsrv\asp.dll" resourceType="File" requireAccess="None" allowPathInfo="true" preCondition="bitness64"/>
</handlers>
<directoryBrowse enabled="false"/>
</system.webServer>
Error :-
You can't log directly from WCF into HTML (or rather, you could but shouldn't).
What you could rather do is throw a FaultException with an appropriate message and have your ASP.NET page handle the Exception and render an HTML page with the appropriate Exception.Message (I prefer Exception.ToString() ) in it.
For more information have a look at this link: Fault Handling in WCF Services

Windows Phone Error Handling: WCF with BasicHttpBinding and TransportWithMessageCredential

I have a WCF service that works as expected when providing proper credentials.
When I try to consume the service with wrong credentials, the service sends an MessageSecurityException error as expected, and I receive an error: "MessageSecurityException was unhandled by user code".
I'm not sure how to handle this exception, since it is raised in the Reference.cs file that is auto-generated and not really under my control:
References.cs
public string EndLogin(System.IAsyncResult result) {
object[] _args = new object[0];
string _result = ((string)(base.EndInvoke("Login", _args, result))); //Here is the error raised
return _result;
}
Ideal would be to check if the service has accepted the credentials instead of relying on an error raised, but have no idea how to check this.
Hope someone can help me, so my App don't have to crash on each wrong login ;)
Web.config : Service:
<?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>
<services>
<service name="BiBasicService.SalesMarketingService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding"
contract="BiBasicService.ISalesMarketingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpsGetEnabled="true" 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="false"/>
<!-- To enable custom Role validation -->
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="BiBasicService.Security.AuthorizationPolicy, BiBasicService" />
</authorizationPolicies>
</serviceAuthorization>
<!-- To enable custom Username and Password validator-->
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="BiBasicService.Security.CustomValidator, BiBasicService"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</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>
ServiceReferences.ClientConfig : Client:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISalesMarketingService" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="TransportWithMessageCredential" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://PUBLICDOMAIN/BasicHttp/SalesMarketingService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISalesMarketingService"
contract="ServiceReference1.ISalesMarketingService" name="BasicHttpBinding_ISalesMarketingService" />
</client>
</system.serviceModel>
</configuration>
The MessageSecurityException: it's a binding error.
Make sure the binding configuration on server side and client side must match.
Please post the server side web.config and client side web.config
You may want to look into the IErrorHandler interface, which would allow you to handle the exception at a more “global level”. The IErrorHandler is an extension that allows explicitly control the behavior of the application when an exception is thrown, implement the IErrorHandler interface and add it to the Dispatcher’s ErrorHandlers property. IErrorHandler enables you to explicitly control the SOAP fault generated, decide whether to send it back to the client, and perform associated tasks, such as logging. Error handlers are called in the order in which they were added to the ErrorHandlers property.
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx
http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/07/wcf-extensibility-ierrorhandler.aspx

Categories

Resources