Error while consuming WCF service in Windows Service - c#

I have added wcf service in "Windows Service" as service reference. but when i try to create instance it simply gives me following error
"Could not find default endpoint element that references contract
'ServiceReference1.IClientService' in the ServiceModel client
configuration section. This might be because no configuration file was
found for your application, or because no endpoint element matching
this contract could be found in the client element."
Code
pushNotification push_notification = new pushNotification();
var proxy = new ServiceReference1.ClientServiceClient();
using (var scope = new OperationContextScope(proxy.InnerChannel))
{
// Add a HTTP Header to an outgoing request
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
requestMessage.Headers["Authorization"] = "Push Notification";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
push_notification = proxy.GetPendingNotification();
}
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:4567/ClientService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IClientService"
name="BasicHttpBinding_IService1" behaviorConfiguration="webHttpBehavior" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>

Be sure you put the endpoint information in your main App.config or Web.config.
If you've added the service reference in a separate project you need to copy the config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:4567/ClientService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IClientService"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
In your startup project App.config/Web.config!

Related

WCF : Client > Endpoint > Error : Invalid URI on working URL

I am setting up a WCF Selfhosted solution to use as a WCF Router and am having a little trouble in getting the service started.
The application code is
public class Program
{
static void Main(string[] args)
{
ServiceHost routingHost = new ServiceHost(typeof(RoutingService));
routingHost.Open();
Console.WriteLine("Routing Service is running");
Console.WriteLine("Press [Enter] to exit");
Console.ReadLine();
routingHost.Close();
}
}
and the App.Config Services Section is
<system.serviceModel>
<services>
<service name="System.ServiceModel.Routing.RoutingService">
<endpoint address="net.tcp://localhost:8009/proposalRouter"
binding="netTcpBinding"
contract="System.ServiceModel.Routing.IRequestReplyRouter"
name="proposalRouter" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="true" />
<routing filterTableName="proposalRoutingTable" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netTcpBinding>
<binding sendTimeout="00:45:00" maxReceivedMessageSize="2000000" />
</netTcpBinding>
</bindings>
<routing>
<filters>
<filter name="proposalFilter" filterType="EndpointAddress" filterData="proposalRouter"/>
</filters>
<filterTables>
<filterTable name="proposalRoutingTable">
<add filterName="proposalFilter" endpointName="defaultProposalService"/>
</filterTable>
</filterTables>
</routing>
<client>
<endpoint address="http://localhost:64434/ProposalService.svc"
binding="basicHttpBinding"
contract="*"
name="defaultProposalService"/>
</client>
The error given is :
Invalid URI: The format of the URI could not be determined.
The issue I have narrowed down to client > endpoint but that is the uri of the svc do not sure what the issue is
I would be grateful if someone could show me where I have gone wrong.
The filter in your configuration file is wrong. When the value of filtertype is address, the filterdata should be a URI.
So your filter should look like this:
<filters>
<filter name="proposalFilter" filterType="EndpointAddress" filterData="net.tcp://localhost:8009/proposalRouter"/>
</filters>
For more information about FilterData Property,Please refer to the following link:
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.routing.configuration.filterelement.filterdata?view=netframework-4.8

WCF UserName & Password validation using wshttpbinding notworking

I am new to WCF Service authentication, I was trying to achieve wcfauthentication using wshttpbinding. but i am getting below exception.
Could not find a base address that matches scheme https for the endpoint with binding WSHttpBinding. Registered base address schemes are [http].
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>
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WCFAuth.Service1" behaviorConfiguration="wsHttpBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttp" contract="WCFAuth.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:64765/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="wsHttpBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFAuth.ServiceAuthanticator, WCFAuth"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</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>
Service Authentication class:
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Linq;
using System.ServiceModel;
using System.Web;
namespace WCFAuth
{
public class ServiceAuthanticator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
string AppUserName = "ABC";
string AppPwd = "abc";
try
{
if (userName.ToLower() != AppUserName.ToLower() && password != AppPwd)
{
throw new FaultException("Unknown Username or Incorrect Password");
}
}
catch (Exception ex)
{
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
Client Side config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<!--<binding name="base" />-->
<binding name="base">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:64765/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="base" contract="WCFAuth.IService1" name="base" />
</client>
</system.serviceModel>
</configuration>
Consumer:
class Program
{
static void Main(string[] args)
{
try
{
WCFAuth.Service1Client client = new WCFAuth.Service1Client();
client.ClientCredentials.UserName.UserName = "test";
client.ClientCredentials.UserName.Password = "test";
var temp = client.GetData(1);
Console.WriteLine(temp);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
I am getting attached exception when i try to browser svc file.
Can someone correct me, where i am committing mistake, thanks in advance.
The problem here is that you are using a WSHttpBinding with Transport Security, but the base address you set is http. It is not possible to work with http here, because you are sending credentials over the wire.
Either change it to https, or create a second binding configuration for development purposes. One with Transport Security (https), and a second without (http).
Also make sure that your clients binding matches the binding from your server.
As Marc mentioned, we are supposed to provide a certificate when hosting the service. there might be something amiss during the process of hosting the service.
Here is a reference configuration, wish it is useful to you.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WCFAuth.Service1" behaviorConfiguration="wsHttpBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttp" contract="WCFAuth.IService1">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="wsHttpBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFAuth.ServiceAuthanticator, WCFAuth"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Then we should add a https binding in IIS Site Bindings module.
The service address would be https://x.x.x.x:8865/Service1.svc
One thing must be noted that we should trust the service certificate when we call the service by adding service reference.
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
ServiceReference2.Service1Client client = new ServiceReference2.Service1Client();
client.ClientCredentials.UserName.UserName = "jack";
client.ClientCredentials.UserName.Password = "123456";
Besides, if we use SecurityMode.Message, we are supposed to provide a certificate in code snippets.
<serviceCredentials>
<serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" findValue="869f82bd848519ff8f35cbb6b667b34274c8dcfe"/>
<userNameAuthentication customUserNamePasswordValidatorType="WcfService1.CustUserNamePasswordVal,WcfService1" userNamePasswordValidationMode="Custom"/>
</serviceCredentials>
Feel free to let me know if there is anything I can help with.

WCF service endpoint not accessible in self-hosting

I have created a IDummyService contract implemented by DummyService. I am trying to self-host this service using the following configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<services>
<service name="DummyService.DummyService" behaviorConfiguration="MEX">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/" />
</baseAddresses>
</host>
<endpoint address="DummyService"
binding="basicHttpBinding"
contract="DummyService.IDummyService"/>
<endpoint address="net.tcp://localhost:8734/DummyService/"
binding="netTcpBinding"
bindingConfiguration = "TransactionalTCP"
contract="DummyService.IDummyService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netTcpBinding>
<binding name = "TransactionalTCP" transactionFlow = "true"/>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name = "MEX">
<serviceMetadata/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The Service Host code that runs fine and starts these endpoints. However, when I try to access the following endpoints I get error as Page isn't working in Chrome browser.
http://localhost:8733/DummyService/
http://localhost:8733/mex/
However, I can access the page http://localhost:8733/
I don't understand why is that.
I thought the endpoint address is address entry for that endpoint appended to host's baseaddress
Any ideas what I am doing wrong ?
Thanks.
You have applied the attribute behaviorConfiguration="MEX" but didnt make use of it,you need to enable the metadata discovery which is false by default in WCF for security reasons.
<serviceBehaviors>
<behavior name = "MEX">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
Now when you browse the http://localhost:8733/DummyService/ and http://localhost:8733/mex/ ,a blank page will be displayed in the browser,instead of default error page.
And also if you want to test the net.tcp endpoint you can use WCFtestclient.exe.

Customizing ServiceAuthorizationManager for WCF Issue

I have created custom ServiceAuthorizationManager as "CustomUserNamePasswordValidator" for my WCF project. below is the snippet of my project. I want my wcf to call up this authorication class before it actually start calling on WCF API but this is not happening. My "Login" WCF API is calling paraller to this authorization class. so when there is call by client to Login it calls both
"CustomUserNamePasswordValidator" and Login method simultaneously.
Authorization Class
public class CustomUserNamePasswordValidator : ServiceAuthorizationManager
{
HttpRequestMessageProperty httpProperties;
string operationName;
protected override bool CheckAccessCore(OperationContext operationContext)
{
operationName = GetOperationName(operationContext);
httpProperties = (HttpRequestMessageProperty)operationContext.IncomingMessageProperties["httpRequest"];
string authHeader = httpProperties.Headers[HttpRequestHeader.Authorization];
string subno = string.Empty;
string password = string.Empty;
string version = string.Empty;
string credntialType = string.Empty;
string[] credentials = authHeader.Split(':');
credntialType = credentials[0];
password = credentials[1];
if (!AuthorizeUser(password))
{
throw new ArgumentException("401:Token invalid or expired.(0x000)");
}
}
}
private int AuthenticateUser(string subno, string pin, string version)
{
}
}
WCF Client Service Snippet
public class ClientService : IClientService
{
public wsLoginResult LoginUser()
{
HttpRequestMessageProperty httpReqProps = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties["httpRequest"];
string res = httpReqProps.Headers[HttpRequestHeader.Authorization];
foreach (var item in res.Split(':'))
ActivityLog("Activity", "Login Steps", item, item);
}
}
Web.Config Snippet
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="wmas_subsConnectionString" connectionString="Data Source=WT;Initial Catalog=wmas;User ID=sa;Password=ra3?" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation targetFramework="4.5" debug="true"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<client>
<endpoint address="http://192.168.1.12:7002/MobileApplicationWS/MobileApplicationApiWSImplService"
binding="basicHttpBinding" bindingConfiguration="MobileApplicationApiWSPortBinding"
contract="VASService.MobileApplicationApiWS"
name="MobileApplicationApiWSPort" />
</client>
<services>
<service name="ClientService.ClientService" behaviorConfiguration="ClientService.ServiceBehavior">
<endpoint address=""
binding="webHttpBinding" bindingConfiguration="webHttpBindingConfiguration"
contract="ClientService.IClientService" behaviorConfiguration="webBehaviour"/>
<endpoint address="stream"
binding="webHttpBinding" bindingConfiguration="webHttpBindingConfigurationStreamed"
contract="ClientService.IClientService" behaviorConfiguration="webBehaviour"/>
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="MobileApplicationApiWSPortBinding" />
</basicHttpBinding>
<webHttpBinding>
<binding name="webHttpBindingConfiguration" />
<binding name="webHttpBindingConfigurationStreamed" transferMode="StreamedResponse" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ClientService.ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType="ClientService.CustomUserNamePasswordValidator, ClientService" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</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>
</configuration>
The reason why your solution doesn't work is that CustomUserNamePasswordValidator can't be used in a RESTful service. Take a look at: http://msdn.microsoft.com/en-us/library/aa354513(v=vs.110).aspx
The example uses SOAP and defines the behaviour of the endpoint which activates serviceAuthorization tag. If you don't define the security of the endpoint the serviceAuthorization simply won't work.
<bindings>
<wsHttpBinding>
<!-- username binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
In a RESTful service there is no SecurityMode = Message, there are only 3: None/Transport/TransportCredentialOnly. Read on about it here: http://msdn.microsoft.com/en-us/library/bb924478(v=vs.110).aspx
clientCredentialType="UserName" is only available in Message.
You can try defining the endpoint security mode to: Transport and then the credential type to: Basic/Certificate/Digest/None/Ntlm/Windows, but seeing as your solution is none of these not sure how well that will work.
There is (I think) a better way of doing authentication if you are extracting headers and not using any "approved" way. Try implementing an extension service: http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iparameterinspector(v=vs.110).aspx
Good Luck!

Upload Image from iOS to WCF, error 415(unsupported media)

I'm trying to upload a photo taken by the iphone to the WCF RESTful server, i've looked all over the web for examples and other answers around the issue, but i can't give with the solution.
The app is written in iOS6, and i'm using AFNetworking 2.0 to upload the image. As in the simulator the camera doesn't work, i've been trying with a library photo. I think the problem is in format differences, WCF is requesting for a Stream parameter, and i don't know how AFNetworking is sending the info...
Here is the WCF code:
[WebInvoke(Method = "POST", UriTemplate = "FileUpload")]
public void FileUpload(Stream stream)
{
try
{
byte[] buffer = new byte[10000];
stream.Read(buffer, 0, 10000);
FileStream f = new FileStream("C:\\temp\\sample.jpg", FileMode.OpenOrCreate);
f.Write(buffer, 0, buffer.Length);
f.Close();
stream.Close();
System.Console.WriteLine("Recieved the image on server");
}
catch (Exception e)
{
System.Console.WriteLine("ERROR: " + e.ToString());
}
}
iOS code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"Users/juan/Library/Application Support/iPhone Simulator/6.1/Media/DCIM/100APPLE/IMG_0001.JPG"];
[manager POST:#"http://192.168.2.3:8732/wave/FileUpload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Testing the web service in fiddler, it throws the same error by sending an image, 415 unsupported media.
I let the app.config of the server:
<configuration>
<system.web>
<httpRuntime maxRequestLength="2097151"
useFullyQualifiedRedirectUrl="true"
executionTimeout="14400" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfJsonRestService.waveWS">
<endpoint address="http://localhost:8732/wave"
binding="wsHttpBinding"
bindingConfiguration="wsHttp"
contract="WcfJsonRestService.IWaveWS"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="wsHttp" maxReceivedMessageSize ="50000000" messageEncoding="Mtom" maxBufferPoolSize="50000000" >
<readerQuotas maxArrayLength="50000000" />
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
<system.diagnostics>
Any idea or suggestion how to solve this?
Every idea is welcome
EDIT:
Finally i solved myself, the problem was in the app.config.
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebConfiguration"
maxBufferSize="65536"
maxReceivedMessageSize="2000000000"
transferMode="Streamed">
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WcfJsonRestService.waveWS">
<serviceMetadata httpGetEnabled="true" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfJsonRestService.waveWS">
<endpoint address="http://localhost:8732/wave"
binding="webHttpBinding"
behaviorConfiguration="WebBehavior"
bindingConfiguration="WebConfiguration"
contract="WcfJsonRestService.IWaveWS"/>
</service>
</services>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

Categories