In WCF While Debugging a service, Metadata Exchange error occurs - c#

I am trying to implement WCF Duplex Application with wsDualHttpBinding.
I am following steps given at below link:
Duplex WCF Services
When I run the service it shows "Metadata Exchange Error"
I am attaching my code here.
Kindly Help.
[1] Service1.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
namespace WCFDuplex
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class CalculatorService : ICalculatorDuplex
{
double result;
string equation;
ICalculatorDuplexCallback callback = null;
public CalculatorService()
{
result = 0.0D;
equation = result.ToString();
callback = OperationContext.Current.GetCallbackChannel<ICalculatorDuplexCallback>();
}
public void Clear()
{
callback.Equation(equation + "=" + result.ToString());
result = 0.0D;
equation = result.ToString();
}
public void AddTo(double n)
{
result += n;
equation += " + " + n.ToString();
callback.Equals(result);
}
public void SubtractFrom(double n)
{
result -= n;
equation += " + " + n.ToString();
callback.Equals(result);
}
public void MultiplyBy(double n)
{
result *= n;
equation += " * " + n.ToString();
callback.Equals(result);
}
public void DivideBy(double n)
{
result /= n;
equation += " / " + n.ToString();
callback.Equals(result);
}
}
}
[2] IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCFDuplex
{
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples" , SessionMode = SessionMode.Required, CallbackContract = typeof(ICalculatorDuplexCallback))]
public interface ICalculatorDuplex
{
[OperationContract(IsOneWay = true)]
void Clear();
[OperationContract(IsOneWay = true)]
void AddTo(double n);
[OperationContract(IsOneWay = true)]
void SubtractFrom(double n);
[OperationContract(IsOneWay = true)]
void MultiplyBy(double n);
[OperationContract(IsOneWay = true)]
void DivideBy(double n);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
public interface ICalculatorDuplexCallback
{
[OperationContract(IsOneWay = true)]
void Equals(double result);
[OperationContract(IsOneWay = true)]
void Equation(string eqn);
}
}
[3] 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>
<services>
<service behaviorConfiguration="CalculatorServiceBehavior" name="WCFDuplex.CalculatorService">
<endpoint address="" binding="wsDualHttpBinding" contract="WCFDuplex.ICalculatorDuplex"/>
<endpoint address="mex" binding="netTcpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:12029/Service1.svc"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="wsDualHttpBinding" 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>

1) in your web.config you have your meta endpoint using the wrong binding. Change it from netTcpBinding to mexHttpBinding
<service behaviorConfiguration="CalculatorServiceBehavior" name="WCFDuplex.CalculatorService">
<endpoint address="" binding="wsDualHttpBinding" contract="WCFDuplex.ICalculatorDuplex"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:12029/Service1.svc"/>
</baseAddresses>
</host>
</service>
2) you have your schema set to https:// but you appear to be using it over http:// Change your schema to http://
<protocolMapping>
<add binding="wsDualHttpBinding" scheme="http" />
</protocolMapping>

Remove the MEX endpoint. Mex endpoints require anonymous authentication to be enabled.
<services>
<service behaviorConfiguration="CalculatorServiceBehavior" name="WCFDuplex.CalculatorService">
<endpoint address="" binding="wsDualHttpBinding"
contract="WCFDuplex.ICalculatorDuplex"/> </endpoint>
</service> </services>
if still the problem persist then please check What is the identity of IIS app pool you are using? The identity need has permission to access %windir%\temp directory. Otherwise you are unable to retrieve metadata information.

Related

Call a WCF service with a HttpClient

I have to call a WCF service. The WCF service is on and I can edit its configuration.
I want to create a client that calls the service. I cannot add the service reference to my client, so I am trying to call it with a HttpClient.
The client side code:
using (var client = new HttpClient())
{
//soapString is my input class serialized
var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
using (var postResponse = client.PostAsync("http://localhost:52937/Attempts.svc/", content).Result)
{
string postResult = postResponse.Content.ReadAsStringAsync().Result;
}
}
The server side code:
[ServiceContract]
public interface IAttempts
{
[OperationContract]
void ReceiveAttemptResult(ReceiveAttemptResultInput result);
}
public class Attempts : IAttempts
{
string _backendUrl;
public void ReceiveAttemptResult(ReceiveAttemptResultInput result)
{
//...
}
}
And in the end the web.config server side:
<system.serviceModel>
<services>
<service name="it.MC.Listeners.Attempts">
<endpoint address="" contract="it.MC.Listeners.IAttempts" binding="basicHttpBinding"/>
<endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
When I call the service, I just obtain an empty string and I cannot stop in debug inside the service... What's wrong?
Thank you
Just in case this bedevils anyone else. Thank you #Disappointed for your missing piece of the puzzle, it prompted me to run the thing in WCF Test Client with Fiddler open to see what I was missing:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/IMyService/Mymethod_Async");
string soapEnvelope = "<s:Envelope xmlns:s= \"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><Mymethod_Async xmlns=\"http://tempuri.org/\"/></s:Body></s:Envelope>";
var content = new StringContent(soapEnvelope, Encoding.UTF8, "text/xml");
HttpResponseMessage hrm = httpClient.PostAsync("http://MyService.MyDomain.com/MyService.svc", content).Result;

WCF restful service not found

Hi all I'm trying to build WCF rest (Ajax enabled) I watch some tutorial in the YouTube as well as I read some questions about this topic in Stackoverflow.
I found some missing element in my web.config I thought the problem was completely fixed, but unfortunately I'm facing new problem now that is service not found.
this is web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="AjaxAndWCF.GetEmployee" behaviorConfiguration="ServiceBehavior">
<endpoint address="../GetEmployee.svc" behaviorConfiguration="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior"
binding="webHttpBinding" contract="AjaxAndWCF.IGetEmployee" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:51520/GetEmployee.svc/"/>
</baseAddresses>
</host>
</service>
</services>
this is the service
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GetEmployee : IGetEmployee
{
public Employee byId(int id)
{
Employee emp = new Employee();
String strcon = ConfigurationManager.ConnectionStrings["WCFTOAJAXT1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strcon))
{
SqlCommand cmd = new SqlCommand("ProGetEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#Id";
parameter.Value = id;
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
emp.Id = Convert.ToInt32(rdr["Id"]);
emp.Name = rdr["Name"].ToString();
emp.Nationality = rdr["Nationality"].ToString();
emp.Email = rdr["Email"].ToString();
}
}
return emp;/*
return new Employee()
{
Id = 1,
Name = "test",
Nationality = "test",
Email ="test#test.com"
};*/
}
}
this is the service contract
[OperationContract]
[WebInvoke(UriTemplate = "/byId?id=id",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
Employee byId(int id);
The Address in the endpoint is BASED off of the base address. Since you don't seem to have any other endpoints, you may as well hang your RESTFUL webservice off of the root address...blank out the address in your endpoint like below and let me know if this fixes it.
<service name="AjaxAndWCF.GetEmployee"
behaviorConfiguration="ServiceBehavior">
<endpoint address=""
behaviorConfiguration="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior"
binding="webHttpBinding"
contract="AjaxAndWCF.IGetEmployee" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:51520/GetEmployee.svc/"/>
</baseAddresses>
</host>
</service>
And then your url will be http://localhost:51520/GetEmployee.svc/byid?id=5
I usually format my urls like "/byid/{id}" so I haven't tried to see if this method works, but I'm assuming you got that code from somewhere.

function called twice with WCF

I am using a DuplexChannelFactory to connect my client to my server and what I want to do now is connect the server to each client that will register on the server. But every time I launch a client, my "init()" function is ran twice. And my DuplexChannelFactory on the server side doesn't work.
Here is how I open my server for clients :
host = new ServiceHost(typeof(NewServeur.NewServeur));
host.Open();
with its App.Config :
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MEX">
<serviceMetadata />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MEX" name="NewServeur.NewServeur">
<endpoint address="IProxyNewServeur" binding="netTcpBinding"
bindingConfiguration="configWin" name="NetTcpEndpoint" contract="ProxyNewServeur.IProxyNewServeur" />
<endpoint address="MEX" binding="mexTcpBinding" bindingConfiguration=""
name="MexTcpEndpoint" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://192.156.142.176:8080/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="configWin">
<security mode="None"></security>
</binding>
</netTcpBinding>
</bindings>
</system.serviceModel>
Here is how I connect my client to my server :
void init()
{
ServiceCablingCallback ServiceCablingCallback = new ServiceCablingCallback();
ServiceCablingCallback.ClientNotified += ServiceCablingCallback_ClientNotified;
this._instanceContext = new InstanceContext(ServiceCablingCallback);
this.factory = new DuplexChannelFactory<ProxyNewServeur.IProxyNewServeur>(_instanceContext, "configClient");
this._serviceCablingClient = factory.CreateChannel();
this._clientId = _serviceCablingClient.Subscribe();
}
with its App.Config
<system.serviceModel>
<client>
<endpoint address="net.tcp://192.156.142.176:8080/IProxyNewServeur"
binding="netTcpBinding" bindingConfiguration="configWin" contract="ALSTEF.Cabling.ProxyNewServeur.IProxyNewServeur"
name="configClient" />
</client>
<bindings>
<netTcpBinding>
<binding name="configWin">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
This works fine, but now I want to do the reverse thing, meaning connecting the server to the client. In order to do so, I added those lines before the last line of my client :
host = new ServiceHost(typeof(Service), new Uri(_serviceCablingClient.getIp()));
host.Open();
with getIp() returning the Ip address + the port 4242 of my client.
and this to the client App.config
<behaviors>
<serviceBehaviors>
<behavior name="MEX">
<serviceMetadata />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MEX" name="Client.Model.Service">
<endpoint address="IClientFunction" binding="netTcpBinding" bindingConfiguration="ClientConfig"
name="NetTcpEndpoint" contract="ProxyNewServeur.IClientFunction" />
<endpoint address="MEX" binding="mexTcpBinding" bindingConfiguration=""
name="MexTcpEndpoint" contract="IMetadataExchange" />
</service>
</services>
<!-- in the bindings html tag -->
<binding name="ClientConfig">
<security mode="None" />
</binding>
And I modified the _serviceCablingClient.Subscribe() by adding those lines (so in the server)
public Guid Subscribe()
{
ProxyNewServeur.INewServeurCallback callback =
OperationContext.Current.GetCallbackChannel<ProxyNewServeur.INewServeurCallback>();
System.ServiceModel.Channels.RemoteEndpointMessageProperty endpointProperty =
OperationContext.Current.IncomingMessageProperties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
Guid clientId = Guid.NewGuid();
if (callback != null)
{
lock (clientsCallback)
{
clientsCallback.Add(clientId, callback);
}
}
/* code I added */
string addr = "net.tcp://" + endpointProperty.Address + ":" + "4242" + "/IClientFunction";
ClientCallback cb = new ClientCallback();
var Okvp = new KeyValuePair<Guid, DuplexChannelFactory<ProxyNewServeur.IClientFunction>>(clientId,
new DuplexChannelFactory<ProxyNewServeur.IClientFunction>(new InstanceContext(cb), "configServer",
new EndpointAddress(addr)));
this.DictClient.Add(Okvp, Okvp.Value.CreateChannel());
this.DictClient[Okvp].CreateCallbackChannel();
/* end code I added */
}
And I added this to the server App.config
<client>
<endpoint binding="netTcpBinding" bindingConfiguration="ClientConfig" contract="ProxyNewServeur.IClientFunction" name="configServer" />
</client>
<!-- in the bindings html tag -->
<binding name="ClientConfig">
<security mode="None" />
</binding>
Here is how I define my ProxyServeur file
namespace ProxyNewServeur
{
[ServiceContract(CallbackContract = typeof(INewServeurCallback))]
public interface IProxyNewServeur
{
[OperationContract]
Guid Subscribe();
[OperationContract]
string getIp();
}
[ServiceContract]
public interface INewServeurCallback
{
[OperationContract(IsOneWay = true)]
void HandleMessage(Message message);
}
[ServiceContract(CallbackContract = typeof(IClientCallback))]
public interface IClientFunction
{
[OperationContract(IsOneWay = true)]
void CreateCallbackChannel();
}
[ServiceContract]
public interface IClientCallback
{
[OperationContract(IsOneWay = true)]
void BroadcastToServer(bool isActive, Guid ClientId);
}
}
Now When I launch a client the line
DictClient[Okvp].CreateCallbackChannel();
won't work and I will go twice in the
init()
{ /* code*/
}
function.
I have no idea why this is happening. I did the exact same thing in a test project and it worked fine.
EDIT
As it turns out, you cannot have a DuplexChannelFactory<> and a ServiceHost in the same method. So what I did is that I added a new Class "DoubleConnection" that have only one attribute.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class DoubleConnection : ProxyNewServeur.IClientFunction
{
public ServiceHost host;
public void CreateCallbackChannel()
{}
public void isActive()
{}
}
and in the init() function I removed
host = new ServiceHost(typeof(Service), new Uri(_serviceCablingClient.getIp()));
host.Open();
and added
varClass = new DoubleConnection();
varClass.host = new ServiceHost(typeof(DoubleConnection), new Uri(_serviceCablingClient.getIp()));
varClass.host.Open();
I works fine now but I still don't know why you cannot have a DuplexChannelFactory<> and a ServiceHost in the same method.

"No default endpoint found" when starting WCF client

I have a Windows Service which represents the WCF-Host and a WPF-Client-Application wich represents the WCF-Client.
The communication should be duplex so I went with WSDualHttpBinding.
At first I install and start my Service which opens a WCF connection after that I start my WPF app and I get the following error (I translated it):
No default endpoint was found to the contract
\ " WCFCloudManagerFolderWatcherService.Interfaces.IFilesDuplex \ " in the service model client configuration section
refers. This may be caused by: For the purposes of no configuration file was found
or in the client element no endpoint element was found , which corresponded to this contract .
Contracts:
IFilesDuplex-Contract:
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode = SessionMode.Required,
CallbackContract = typeof(IFilesDuplexCallback))]
public interface IFilesDuplex
{
[OperationContract(IsOneWay = true)]
void Update();
}
IFilesDuplexCallback:
interface IFilesDuplexCallback
{
[OperationContract(IsOneWay = true)]
void Equals(string[] result);
}
ClientSide
CallbackHandler:
class CallbackHandler : IFilesDuplexCallback
{
public event Action<string[]> ReceivedList = delegate { };
public void Equals(string[] result)
{
this.ReceivedList(result);
}
}
The Client itself:
class FilesDuplexClient : DuplexClientBase<IFilesDuplex>, IFilesDuplex
{
public FilesDuplexClient(InstanceContext callbackCntx)
: base(callbackCntx)
{
}
public void Update()
{
base.Channel.Update();
}
}
And the Code from the Main Window, where the error is thrown:
CallbackHandler ch = new CallbackHandler();
ch.ReceivedList += ch_ReceivedList;
// Construct InstanceContext to handle messages on callback interface
InstanceContext instanceContext = new InstanceContext(ch);
// Create a client
FilesDuplexClient client = new FilesDuplexClient(instanceContext);
client.Update();
Serverside (Windows Service)
FileProtocoll-Class (Server code)
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class FileProtocoll : IFilesDuplex
{
IFilesDuplexCallback Callback
{ get { return OperationContext.Current.GetCallbackChannel<IFilesDuplexCallback>(); } }
void IFilesDuplex.Update()
{
//....
Callback.Equals(null);// just a dummy
//...
}
}
Code in the OnStart-Method (in a Thread):
// Step 1 Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8899/CloudManager/CommunicationChannel1");
// Step 2 Create a ServiceHost instance
if (selfHost != null)
{
selfHost.Close();
}
selfHost = new ServiceHost(typeof(FileProtocoll), baseAddress);
try
{
// Step 5 Start the service.
selfHost.Open();
}
catch (CommunicationException ce)
{
selfHost.Abort();
}
Code in the OnStop-Method (in a Thread):
if (selfHost != null)
{
if (selfHost.State != CommunicationState.Closed)
{
selfHost.Close();
}
selfHost = null;
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior"
name="WCFCloudManagerFolderWatcherService.Communication.FileProtocoll">
<endpoint address="http://localhost:8899/CloudManager /CommunicationChannel1"
binding="wsDualHttpBinding" contract="WCFCloudManagerFolderWatcherService.Interfaces.IFilesDuplex">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true "/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
I finally got it.
Had to make a few changes to my Client app.config and had to turn off security.
app.config(client):
<!-- WCF Client information-->
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_IFilesDuplex">
<security mode="None"/>
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint
address="http://localhost:8899/CloudManager/CommunicationChannel1"
binding="wsDualHttpBinding"
bindingConfiguration="WSDualHttpBinding_IFilesDuplex"
contract="WCFCloudManagerFolderWatcherService.Interfaces.IFilesDuplex"
name="WSDualHttpBinding_IFilesDuplex">
<identity>
<userPrincipalName value="localhost"/>
</identity>
</endpoint>
</client>
and in the app.config for the serverside I also hat to set
<security mode="None"/>
Now the connection works.

How to make a WCF Service work with https?

I am trying to enable https in my WCF service. I've added the SSL certificate to my localhost and I am able to view the WSDL when I use https in the browser. And the WCF service works fine with http without the SSL configuration in the web.config. But as soon as I change it to use https, I get the following error. If anybody can point me to the solution for this issue, it will be helpful as there isn't much reference for this error.
at Microsoft.Http.HttpStageProcessingAsyncResult.Complete(HttpStage stage, Exception e)
at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self)
at Microsoft.Http.HttpStageProcessingAsyncResult..ctor(HttpStageProcessingAsyncState state, AsyncCallback callback, Object user)
at Microsoft.Http.HttpClient.Send(HttpRequestMessage request)
at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content)
at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, Uri uri)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, String uri)
at Microsoft.Http.HttpMethodExtensions.Get(HttpClient client, String uri)
at MobileScreening.Client.CommonTests.LoginPost(HttpClient client, String username, String password) in c:\TFS Projects\MobileScreening\MobileScreening.Client\CommonTests.cs:line 118
My client code where I am making the request to the service
static string LoginPost(HttpClient client, string username, string password)
{
string key = string.Empty;
try
{
var user = new UserCredentials
{
Email = username,
Password = password
};
Console.WriteLine("User Authentication:");
HttpContent content = HttpContentExtensions.CreateJsonDataContract(user);
using (HttpResponseMessage response = client.Post("AuthenticationService.svc/", content))
{
Console.WriteLine(response.Content.ReadAsString());
Console.WriteLine(response.Headers.ToString());
key = response.Headers["MobileScreening"] ?? string.Empty;
}
}
catch (Exception ex)
{
var stack = ex.StackTrace;
var innerException = ex.InnerException;
var message = ex.Message;
}
return key;
}
My interface with the operation contract
public interface IAuthenticationService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
AuthenticationWrapper Authenticate(UserCredentials user);
}
My Service to authenticate users:
public class AuthenticationService : IAuthenticationService
{
public AuthenticationWrapper Authenticate(UserCredentials user)
{
string email = user.Email ?? string.Empty;
string password = user.Password ?? string.Empty;
var authentication = new Authentication();
var authenticationWrapper = new AuthenticationWrapper();
if (!authentication.AuthenticateUser(email, password))
{
const string description = "Authentication failed. Username and/or password is incorrect.";
BLL.Authentication.ThrowAuthorisationFailed(description, email);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
authenticationWrapper.Code = (short)HttpStatusCode.Unauthorized;
authenticationWrapper.Status = HttpStatusCode.Unauthorized.ToString();
authenticationWrapper.Message = description;
return authenticationWrapper;
}
else
{
const string description = "Authentication: Authenticate User";
LogHandler.LogMessage(email, description, Common.Event.LoginSuccessful);
string authorisationKey = authentication.CreateAuthorisationKey(email);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add(Common.AuthorisationHeader, authorisationKey);
ctx.OutgoingResponse.StatusCode = HttpStatusCode.OK;
authenticationWrapper.Code = (short)HttpStatusCode.OK;
authenticationWrapper.Status = HttpStatusCode.OK.ToString();
authenticationWrapper.Message = description;
return authenticationWrapper;
}
}
}
Finally my web.config configuration for the service
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="MobileScreening.ServiceApp.AuthenticationService">
<endpoint address="AuthenticationService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IAuthenticationService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
<service name="MobileScreening.ServiceApp.ProgrammeService">
<endpoint address="ProgrammeService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IProgrammeService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
<service name="MobileScreening.ServiceApp.ActivityService">
<endpoint address="ActivityService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IActivityService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
<service name="MobileScreening.ServiceApp.UserConfigurationService">
<endpoint address="UserConfigurationService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IUserConfigurationService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="Transport">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata 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>
Create a new self signed certificate using your machine name instead of the local host. Configure your solution to use the new certificate and make sure that it is installed in the client machine's under the Trusted Root Certification Authority (in your case, the client is also the server).
Also, you may also try to create the certificate pointing to the machine's fully qualified domain name.

Categories