Configuring WCF JSONP and SOAP Endpoints Listening at the same URI - wcf

I JSONP enabled my WCF ServiceContract. Client is successfully calling the JSONP Service (OperationContract). I have a number of other OperationContracts (using the same ServiceContract) that I want to expose using basicHttpBinding (SOAP) endpoint - using the same URI. I think my Service WebConfig is set up correctly. When doing such a thing, should I be able to Add the Service Reference (proxy) using the VS "Add Service Reference" dialog window? Or do I need to manually generate client code in codebehind? If I need to manually do it, can anyone provide an example? Or is my Service WebConfig not configured correctly? I am calling the JSONP Service using this: http://Flixsit:1000/FlixsitWebServices.svc/jsonp
Thanks so much...
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DefaultBehaviors">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="JSONPBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
<basicHttpBinding>
<binding name="SOAPBinding" />
</basicHttpBinding>
</bindings>
<services>
<service name="Flixsit.Services.FlixsitWebServices" behaviorConfiguration="DefaultBehaviors">
<clear />
<endpoint name="JSONPEndPoint" address="jsonp"
binding="webHttpBinding"
bindingConfiguration="JSONPBinding"
contract="Flixsit.Services.IFlixsitWebServices"
behaviorConfiguration="webHttpBehavior" />
<endpoint name="HttpEndPoint" address=""
binding="basicHttpBinding"
bindingConfiguration="SOAPBinding"
contract="Flixsit.Services.IFlixsitWebServices" />
<host>
<baseAddresses>
<add baseAddress="http://Flixsit:1000/FlixsitWebServices.svc" />
</baseAddresses>
</host>
</service>
</services>

After tooling around for a while I am creating the ChannelFactory like below (in codebehind). Services are now exposed at both endpoints.
try
{
EndpointAddress address = new EndpointAddress("http://Flixsit:1000/FlixsitWebServices.svc");
WSHttpBinding binding = new WSHttpBinding();
ChannelFactory<IFlixsitWebServices> factory = new ChannelFactory<IFlixsitWebServices>(binding, address);
IFlixsitWebServices channel = factory.CreateChannel();
//call the service operation
var customer = channel.GetCustomers();
GridView1.DataSource = customer;
GridView1.DataBind();
//close the channel
((ICommunicationObject)channel).Close();
//close factory
factory.Close();
}
catch (Exception ex)
{
//log ex;
}

Related

WCF JSON Format - while consuming in Client side getting an error message

Client side Code
I have created web application and added service reference to the Client Project
I tried creating a client Object like this:
Service1Client a = new Service1Client();
but getting an error message :
Could not find default endpoint element that references contract 'ServiceReference_test.IService1' 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.
Could you please let me know what mistake am I doing, I am new to WCF please help me
WCF service which returns JSON Format:
namespace WcfService1
{
public class Service1 : IService1
{
public string GetData(string Id)
{
return ("You entered: " + Id);
}
}
}
namespace WcfService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetData/{Id}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped
)]
string GetData(string Id);
// TODO: Add your service operations here
}
}
Web.Config file
<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WcfService1.IService1"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>-->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
You should add following tags in your client App.config or Web.config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding" />
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/fine_service/FineService/soap"
binding="webHttpBinding" bindingConfiguration="WebHttpBinding"
contract="ServiceReference1.IService1" name="WebHttpBinding" />
</client>
</system.serviceModel>
if you have this tags in your cofig file then make sure that client endpoint contract name should be the same as it is in your service endpoint. In your case contract name is IService1
EDIT:
also see this

WCF Discovery returns machine names in metadata (cannot be resolved)

So I have a WCF service hosted in IIS8 (Windows Server 2012). Here's the relevant part of the configuration file:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="MovieCorner.DAL.Service.MovieCornerDalService">
<host>
<baseAddresses>
<add baseAddress="http://192.168.221.101/MovieCorner/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding"
contract="MovieCorner.Commons.Services.IMovieCornerDalService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint kind="udpDiscoveryEndpoint" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True" />
<serviceDiscovery />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
A simple service with a simple binding, and with a discovery endpoint. The service is up and running, everything works fine. Almost...
Here's the code I'm using on the client side (it's just a "unit" test):
var client = new DiscoveryClient(new UdpDiscoveryEndpoint());
var response = client.Find(new FindCriteria(typeof(IMovieCornerDalService)));
Assert.IsNotNull(response);
Assert.IsNotNull(response.Endpoints);
Assert.IsTrue(response.Endpoints.Count > 0);
foreach (var endpoint in response.Endpoints)
{
Console.WriteLine("Address: {0}; Contract: {1}", endpoint.Address, endpoint.ContractTypeNames[0]);
}
The code successfully finds the only running service. The output is the following:
Address: http://ws12-iis8/MovieCorner/MovieCornerDalService.svc;
Contract: http://tempuri.org/:IMovieCornerDalService
The address is returned with the machine name that hosts the service. After the discovery I want to use the service like this:
var endpoint = response.Endpoints[0];
var clientProxy = ChannelFactory<IMovieCornerDalService>.CreateChannel(new BasicHttpBinding(), endpoint.Address);
var user = clientProxy.RegisterUser("1234"); // problem
The actual method call throws an exception, and the inner exception is the following: System.Net.WebException: The remote name could not be resolved: 'ws12-iis8'
The "unit" test runs in my PC, the service is hosted in a VM. I can reach the service at the http://192.168.221.101/MovieCorner/MovieCornerDalService.svc address. But not with the machine name address.
What am I missing? What are my options? How can I retrieve the actual (private) IP of the service hosting VM? I searched for different metadata options, but I'm not a pro in the web world, so I don't know what I'm looking for.
If you need more information, let me know. Thanks for your time!

Invoking WCF service in browser similar to asmx

I have made a WCF service in NET 4.0 and it returns the XML, I have tested it using SoapUI and i can see the required response xml. But my WCF service would be called by 3rd party software and they want to use it through a URL like asmx. I have googled and found that i need to make using REST guidelines. However i have not found a proper link showing making web-service using REST and then accessing the method from the browwer similar to web services.
Below is the interface code which i have used to return the format in XML
public interface IService1
{
[WebGet(
UriTemplate = "/GetDocument/",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml)]
[OperationContract, XmlSerializerFormat]
XmlElement GetDocument();
// TODO: Add your service operations here
}
Below is my config settings.
<system.serviceModel>
<services>
<service name="BritishLandXML.BritishLandXML1" behaviorConfiguration="metadataBehavior">
<endpoint address="" binding="basicHttpBinding" contract="BritishLandXML.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding>
<security mode="None"></security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp helpEnabled="true" faultExceptionEnabled="true" automaticFormatSelectionEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
Please let me know how can i achieve this and what exact settings will be required.

FileTransfer to WCF Service receiving 405

I'm working on a mobile app using PhoneGap, and one of the features involves uploading an image to a web service for processing. I've written a WCF service that's hosted in IIS to accept the image, with a contract that looks like the following:
[ServiceContract]
public interface IImages
{
[OperationContract(Name="UploadImage")]
[WebInvoke(UriTemplate = "?file_key={fileKey}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
ImageResource UploadImage(string fileKey, Stream imageStream);
}
The configuration section in my web.config looks like:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<serviceActivations>
<add service="Services.Images" relativeAddress="images.svc" />
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service behaviorConfiguration="DefaultServiceBehavior" name="Services.Images">
<endpoint behaviorConfiguration="DefaultEndpointBehavior" binding="webHttpBinding" bindingConfiguration="PublicStreamBinding" contract="Services.Contracts.IImages" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="PublicStreamBinding"
maxReceivedMessageSize="2000000000" transferMode="Streamed">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="DefaultEndpointBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
When I attempt to upload a file to the endpoint, using PhoneGap's FileTransfer class, the response returned from the service is a 405 Method Not Allowed. What am I doing wrong here?
UPDATE: The function in my mobile app that's uploading the file is below. This code previous worked fine when pointed to an older ASMX service.
ns.UploadImage = function(){
//alert(ns.Dictionary['LocalImagePath']);
var uri = ns.Dictionary['LocalImagePath'];
try {
var options = new FileUploadOptions();
options.fileKey = uri.substr(uri.lastIndexOf('/')+1) + ".jpeg";
options.fileName = uri.substr(uri.lastIndexOf('/')+1) + ".jpeg";
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(uri, GetServerUrl()+"images.svc?file_key="+options.fileKey, ns.UploadImageSuccess, ns.UploadImageError, options);
} catch (e) {
ns.UploadImageError(e);
}
};
Ok so I think I figured this out. Apparently, when the method is hosted at the root like this, if you don't follow the name of the service in the uri with '/', the request won't get routed correctly. So, in the function that uploads the file, I changed the ft.upload line to the following:
ft.upload(uri, GetServerUrl()+"images.svc/?file_key="+options.fileKey, ns.UploadImageSuccess, ns.UploadImageError, options);
Which worked.

Call HTTPS REST service from WCF

I need to call some REST services from a third parties server over HTTPS. My thinking was that I would create myself a nice little WCF library to handle these calls and deserialise the responses. I'm coming a tad unstuck though.
The services I am trying to call have a test service that simply responds OK.
I have created an OperationContract in my interface as shown below:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "test")]
string Test();
In my service code I have a public method below:
public string Test()
{
ChannelFactory<IService1> factory = new ChannelFactory<IService1>("UMS");
var proxy = factory.CreateChannel();
var response = proxy.Test();
((IDisposable)proxy).Dispose();
return (string)response;
}
My app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<client>
<endpoint address="https://61.61.34.19/serv/ums/"
binding="webHttpBinding"
behaviorConfiguration="ums"
contract="WCFTest.IService1"
bindingConfiguration="webBinding"
name="UMS" />
</client>
<services>
<service name="WCFTest.Service1" behaviorConfiguration="WCFTest.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WCFTest/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract="WCFTest.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ums">
<clientCredentials>
<clientCertificate findValue="restapi.ext-ags.801"
storeLocation="CurrentUser"
x509FindType="FindBySubjectName"/>
</clientCredentials>
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WCFTest.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
<transport clientCredentialType="Certificate" proxyCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
I try to invoke the test method but receive the error "Could not establish trust relationship for the SSL/TLS secure channel with authority '61.61.34.19'."
Can anyone see what I'm missing here?
Any help appreciated. Cheers.
Could not establish trust relationship for the SSL/TLS secure channel with authority '61.61.34.19'.
This typically means there's a problem with the server's SSL cert. Was it self-signed? If so, you have to establish trust for the cert, typically by trusting the issuing CA or installing the cert in the windows cert store.
Try changing the webHttpBinding security setting from "Transport" to "None".