Display Image entity in XML through webservice(SOAP) using C#? - c#

There is an web application, where in it has few entities including image entity.That image is already stored in DB, now i have to access it through webservice and display in XML. Tried converting that image entity to byte[] and as well as String base64. But did not work out. Please help me to resolve this issue. Thanks in advance.

Are you facing issue transmitting the image back?
I converted the image to base64 and returned as a string. It is working fine. What issue did you face there.
But this approach requires update on the maxReceivedMessageSize parameters in WCF service as well as the client.
Side effects : There are some issues with increasing
maxReceivedMessageSize. More memory foot print, might open up DDOS
attacks.
Service Contract
public class ImageService : IImageService
{
public string GetImageData(string path)
{
if (File.Exists(path))
{
return ConvertFile(path);
}
else
return string.Empty;
}
private string ConvertFile(string path)
{
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
}
Service Configuration
<system.serviceModel>
<bindings>
<basicHttpsBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpsBinding>
</bindings>
<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>
Client Code
static void Main(string[] args)
{
ImageService.ImageServiceClient client = new ImageService.ImageServiceClient();
string data = client.GetData(#"C:\Users\v-sridve\Pictures\Travel_Error_New.PNG");
}
Client Configuration
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" maxReceivedMessageSize="1000000" maxBufferSize="1000000" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:7541/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ImageService.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>

Related

WCF Named Pipe in Windows Service using App.Config

I am frustrated. Okay, here is the error.
There was no endpoint listening at net.pipe://localhost/MyIpcAppToService that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
I finally got the App.Config file working, at least no complaints.
Current App.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
<system.serviceModel>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyService.Communication.IpcAppToService">
<endpoint address="net.pipe://localhost/MyIpcAppToService" binding="wsDualHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" contract="MyIpc.IIpcAppToService"/>
<endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/MyService/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<!-- 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>
</behaviors>
<protocolMapping>
<add scheme="http" binding="wsHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" />
</protocolMapping>
<bindings>
<wsDualHttpBinding>
<!-- https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/wshttpbinding -->
<binding name="MyAppToServiceEndpointBinding"
transactionFlow="true"
sendTimeout="00:01:00"
maxReceivedMessageSize="2147483647"
messageEncoding="Mtom">
</binding>
</wsDualHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
<baseAddressPrefixFilters>
<add prefix="http://localhost:8733"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
<appSettings>
<add key="countoffiles" value="7"/>
<add key="logfilelocation" value="abc.txt"/>
</appSettings>
</configuration>
I used to have:
<endpoint address="http://localhost:8733/MyIpcAppToService" ...
and in the Windows Service OnStart() event:
(this following code is now commented out, as of this question post, as the App.config file is supposed to start the named.pipe.)
public Boolean CreatePipeServer()
{
string eventText = $"My Service: CommAppToService::CreatePipeServer(IPC App to Service){Environment.NewLine}";
try
{
if (null != this.ServiceParent.HostIpcAppToService)
this.ServiceParent.HostIpcAppToService = null;
string pipeBaseAddress = #"net.pipe://localhost/MyIpcAppToService";
this.ServiceParent.HostIpcAppToService = new ServiceHost(typeof(IpcAppToService), new Uri(pipeBaseAddress));
NetNamedPipeBinding pipeBinding = new NetNamedPipeBinding()
{
//ReceiveTimeout = new TimeSpan(0, 0, 0, 0, Constants.My_TimeoutMsSendReceive),
//SendTimeout = new TimeSpan(0, 0, 0, 0, Constants.My_TimeoutMsSendReceive),
};
this.ServiceParent.HostIpcAppToService.AddServiceEndpoint(typeof(IIpcAppToService), pipeBinding, "MyIpcAppToService");
this.ServiceParent.HostIpcAppToService.UnknownMessageReceived += HostIpcAppServer_UnknownMessageReceived;
this.ServiceParent.HostIpcAppToService.Faulted += HostIpcAppServer_Faulted;
this.ServiceParent.HostIpcAppToService.Closing += HostIpcAppServer_Closing;
this.ServiceParent.HostIpcAppToService.Closed += HostIpcAppServer_Closed;
this.IpcAppToService = new IpcAppToService();
this.IpcAppToService.ApplyDispatchBehavior(this.ServiceParent.HostIpcAppToService);
this.IpcAppToService.Validate(this.ServiceParent.HostIpcAppToService);
this.ServiceParent.HostIpcAppToService.Open();
return true;
}
I read that the service will AUTOMATICALLY start services placed in the App.Config file, really the MyExeName.exe.config file. I kept looking at the code and saw that it was nearly identical, so I replaced the http:// with net.pipe://.
Sadly, old code, new code, in between code, all nothing. I keep receiving the same error.
I use the following to connect to the service from my desktop application.
public static Boolean ConnectToService()
{
try
{
var callback = new IpcCallbackAppToService();
var context = new InstanceContext(callback);
var pipeFactory = new DuplexChannelFactory<IIpcAppToService>(context, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyIpcAppToService"));
Program.HostIpcAppToService = pipeFactory.CreateChannel();
Program.HostIpcAppToService.Connect();
CommAppToService.IsPipeAppToService = true;
return true;
}
catch (Exception ex)
{
// Log the exception.
Errors.LogException(ex);
}
return false;
}
For whatever it is worth, here is:
Interface
[ServiceContract(SessionMode = SessionMode.Allowed, CallbackContract = typeof(IIpcCallbackAppToService))]
public interface IIpcAppToService
{
[OperationContract(IsOneWay = false)]
[FaultContractAttribute(typeof(IpcAppToServiceFault))]
UInt16 GetServiceId();
...
}
Service:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class IpcAppToService : IIpcAppToService, IErrorHandler
{
public static IIpcCallbackAppToService Callback { get; set; } = null;
public void OpenCallback()
{
IpcAppToService.Callback = OperationContext.Current.GetCallbackChannel<IIpcCallbackAppToService>();
}
public void CloseCallback()
{
IpcAppToService.Callback = null;
}
public void SendMessage(string message)
{
//MessageBox.Show(message);
}
public UInt16 GetServiceId()
{
return Constants.My_Id_AppToService;
}
...
}
Inner Exception from my desktop WinForms Application
(Note, there were no further inner exceptions than this one.):
"The pipe endpoint 'net.pipe://localhost/MyIpcAppToService' could not be found on your local machine."
Why do I keep seeing this error?
UPDATE AFTER 1ST ANSWER
The direction that I would like to take is opposite of the answer, yet the same, namely that the service starts with the App.config and the client uses C# code.
Sadly, I still get the same error.
Revised Server Side App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
<system.serviceModel>
<services>
<service behaviorConfiguration="BehaviorMyService" name="MyService.Communication.IpcAppToService">
<endpoint address="net.pipe://localhost/MyIpcAppToService"
binding="netNamedPipeBinding"
bindingConfiguration="EndpointBindingMyAppToService"
contract="MyIpc.IIpcAppToService"
/>
<endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/MyService/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="BehaviorMyService">
<!-- 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>
</behaviors>
<bindings>
<netNamedPipeBinding>
<!-- https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/wshttpbinding -->
<binding name="EndpointBindingMyAppToService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
transactionFlow="false"
transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxBufferSize="65536"
maxConnections="10"
maxReceivedMessageSize="2147483647"
>
<security mode="None">
<transport protectionLevel="None" />
</security>
</binding>
</netNamedPipeBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
<baseAddressPrefixFilters>
<add prefix="http://localhost:8733"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
<appSettings>
<add key="countoffiles" value="7"/>
<add key="logfilelocation" value="abc.txt"/>
</appSettings>
</configuration>
Revised Client Side C# Code:
var callback = new IpcCallbackAppToService();
InstanceContext context = new InstanceContext(callback);
NetNamedPipeBinding binding = new NetNamedPipeBinding();
binding.Security.Mode = NetNamedPipeSecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/MyIpcAppToService");
var pipeFactory = new DuplexChannelFactory<IIpcAppToService>(context, binding, endpointAddress);
Program.HostIpcAppToService = pipeFactory.CreateChannel();
Program.HostIpcAppToService.Connect();
CommAppToService.IsPipeAppToService = true;
The service throws no exceptions that I can detect, as the EventViewer is clean, just the OnStart() successfully completed message. I know that the system processes the App.config file, as previously when I had errors, the Windows Event Viewer would keep complaining, but not anymore.
Here were some of the Microsoft docs that I used:
netNamedPipeBinding
netNamedPipeBinding2
I did try IO Ninja, but specifying \\.\pipe\MyIpcToService for File Stream, Pipe Listener, and Pipe Monitor, but nothing shows there, even when I try to connect using my WinForms desktop application, which then throws the no pipe listener found exception.
What can be the problem?
<endpoint address="net.pipe://localhost/MyIpcAppToService" binding="wsDualHttpBinding" bindingConfiguration="MyAppToServiceEndpointBinding" contract="MyIpc.IIpcAppToService"/>
Make sure that the service address is in the same form (transport protocol) as the binding type.
TCP(net.tcp://localhost:8000/myservice) NetTcpBinding
IPC(net.pipe://localhost/mypipe) NetNamedPipeBinding
Http/Https(http://localhost:8000/myservice)
Wshttpbinding,Wsdualhttpbinding,basichttpbinding
WebSocket(ws://localhost:3434) Nethttpbinding
MSMQ(net.msmq://localhost/private/myservice) NetMsmqBinding
we are supposed to use NetnamedPipeBinding for the service address. Please refer to my example.
Updated
I have a wcf service using NetNamedPipeBinding hosted in IIS, wish it is useful to you.
Server(wcf service application)
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
}
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
Web.config(Server side)
<system.serviceModel>
<services>
<service behaviorConfiguration="BehaviorMyService" name="WcfService1.Service1">
<endpoint address="MyIpcAppToService"
binding="netNamedPipeBinding"
bindingConfiguration="EndpointBindingMyAppToService"
contract="WcfService1.IService1"
/>
<endpoint address="mex" binding="mexHttpBinding" name="mex" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="BehaviorMyService">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netNamedPipeBinding>
<binding name="EndpointBindingMyAppToService"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
transactionFlow="false"
transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxConnections="10"
maxReceivedMessageSize="2147483647"
>
<security mode="None">
<transport protectionLevel="None" />
</security>
</binding>
</netNamedPipeBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
Enable WCF new feature.
IIS site(enable net.pipe)
Client(console application)
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
var result = client.GetData(34);
Console.WriteLine(result);
Client app.config(auto-generated)
I use the http address(service metadata GET address http://localhost:8733/Service1.svc?wsdl) to generated the configuration.
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IService1">
<security mode="None" />
</binding>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address="net.pipe://mynetpipe/Service1.svc/MyIpcAppToService"
binding="netNamedPipeBinding" bindingConfiguration="NetNamedPipeBinding_IService1"
contract="ServiceReference1.IService1" name="NetNamedPipeBinding_IService1" />
</client>
</system.serviceModel>
Feel free to let me know if there is anything I can help with.

Can't get file size when loading from WCF service host by web browser

I have some test WCF service with streamed webHttpBinding, which allows to download files by web browser. The problem is browser doesn't show file size and download progress.
This is the service contract:
[ServiceContract]
public interface IDataTransferService
{
[WebGet(UriTemplate = "download?file={fileName}")]
Stream GetDownloadStream(string fileName);
}
This is the service implementation:
public sealed class DataTransferService : IDataTransferService
{
public Stream GetDownloadStream(string fileName)
{
var context = WebOperationContext.Current;
var stream = File.OpenRead(fileName);
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = $"attachment; filename={Path.GetFileName(fileName)}";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
WebOperationContext.Current.OutgoingResponse.Headers["Content-Length"] = stream.Length.ToString();
return stream;
}
}
And this is the service configuration:
<system.serviceModel>
<services>
<service name="WcfStreamingTest.Server.DataTransferService">
<endpoint contract="WcfStreamingTest.IDataTransferService"
address="http://localhost:8000/streamingtest/api/transfer"
binding="webHttpBinding"
bindingConfiguration="streamedWeb"
behaviorConfiguration="web"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="streamedWeb" transferMode="Streamed" sendTimeout="00:15:00" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Name of file shows correctly, but information about file size is missing.
Try to change transferMode to StreamedResponse
<binding name="streamedWeb" transferMode="StreamedResponse" sendTimeout="00:15:00" />

Sending JSON to a C# WCF-service results in : Request Entity Too Large

I have been looking around and checked several answers but I still keep running into the same problem.
I have a WCF-service which receives data as JSON and then processes it.
I have a console-application which calls this service.
But I keep running into the same problem: 'The remote server returned an unexpected response: (413) Request Entity Too Large.
In my console-application config I have :
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IPaymentBehaviorService" allowCookies="true"
maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:50068/PaymentBehaviorService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IPaymentBehaviorService"
contract="PaymentBehaviorServiceService.IPaymentBehaviorService"
name="BasicHttpBinding_IPaymentBehaviorService" />
</client>
</system.serviceModel>
My server-config :
<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="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
One line in the data that is being sent, looks like :
{ \"ReqId\":\"79\",\"TaxNbr\":\"889638963\",\"Amount\":\"29,4\",\"Invoice\":\"10/2330\",\"InvDate\":\"19/04/2018 0:00:00\",\"ExpDate\":\"19/04/2018 0:00:00\" }
I can only send about 450 of those lines in one request.
I need to raise that number of lines to something like 1500 or even more.
How can I do that?
I have found a lot of similar questions but none that gave me a solution.
Have you played around with TransferMode attribute in the basicHttpBinding; setting the mode to "streaming"

WCF Service TransportWithMessageCredentials Customer validator

I have configured a new Azure hosted WCF service with a custom username validator. The validator class will validate username and passwords from an existing aspnetUsers table in an Azure database.
I have configured the service using TransportWithMessageCredentials binding so the clients will be providing their usernames and passwords in clear text in the request.
My code will then look up the user and get their hashed password from the database and then use this to hash the password sent via the service. If they match then allow the request.
to validate the password I am using this code.
public static bool checkPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
So my question really is, Is sending the username and passwords in this way secure enough? As everything is going over https I am assuming it is but would like some guidance as I am fairly new to security in general.
The service will also be IP restricted.
Here is my service model config.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehaviour">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyValidatorClass,MyNameSpace" />
</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>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="HttpBinding" maxReceivedMessageSize="2097152" receiveTimeout="00:02:00" sendTimeout="00:02:00">
</binding>
<binding name="HttpsBinding" maxReceivedMessageSize="2097152" receiveTimeout="00:02:00" sendTimeout="00:02:00">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="MyService" behaviorConfiguration="MyServiceBehaviour">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="HttpsBinding" contract="MyContract" />
<host>
<baseAddresses>
<add baseAddress="https://MyServiceInAzure.net/" />
</baseAddresses>
</host>
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
And here is what the clients will be using:
Client.Service call = new Client.ServiceClient();
call.ClientCredentials.UserName.UserName = "MyUsername";
call.ClientCredentials.UserName.Password = "MyPassword";
var result = call.PostCall("Hello World");
Thanks
So my question really is, Is sending the username and passwords in this way secure enough?
Yes. Since everything which send by HTTPS will be encrypted, you could send the user name and password without encrypted manually. Per my opinion, it is not recommend to send user name and password every time when sending request to your service. I suggest you generate a token at the first time and using the token to validate your request for a period of time.

WCF adding second endpoint using computer name and local domain

I'm not very experienced with WCF, as such I'm a little stuck with this one, I allow my WCF service to configure it's own endpoints (my manual attempts have been less than successful). Now this works fine appart from one issue, It adds a second endpoint using the local machine name, and the local windows domain.
My Config file is such:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<useRequestHeadersForMetadataAddress>
<defaultPorts>
<add scheme="https" port="443"/>
</defaultPorts>
</useRequestHeadersForMetadataAddress>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
However when adding this WCF to a WPF application, it generates the following config (Url changed for security)
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IAdminService">
<security mode="None">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
<binding name="BasicHttpsBinding_IAdminService">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://machinename.domain.local/PortalServices/AdminService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IAdminService"
contract="AdminService.IAdminService" name="BasicHttpBinding_IAdminService" />
<endpoint address="https://mysite.co.uk/PortalServices/AdminService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpsBinding_IAdminService"
contract="AdminService.IAdminService" name="BasicHttpsBinding_IAdminService" />
</client>
</system.serviceModel>
As you can see, it adds a working URL and a local domain URL
http://machinename.domain.local/PortalServices/AdminService.svc
How can i prevent this from being added? as it becomes a bit of a pain having to remember to manually remove it after every deploy/service update.
As Requested, this is one of the Interface classes.
[ServiceContract]
public interface IAdminService
{
[OperationContract]
List<PortalApp> GetApplications();
[OperationContract]
int AddApplication(string AppName, string Desc, string version, bool enabled);
[OperationContract]
bool EditApplication(int appid, string AppName, string Desc, string version, bool enabled);
[OperationContract]
bool AddAppAccess(int appid, Int16 uid);
[OperationContract]
bool RemAppAccess(int appid, Int16 uid);
[OperationContract]
List<PortalUser> GetUsers();
}
Ok, thanks to Jontatas mentioning the fact the endpoints have seperate binding types it got me thinking.
Turns out i had forgotten to remove the http binding from IIS itself (which is not used). Removing that binding from IIS also removed the incorrect binding in the generated config.

Categories

Resources